;

/**
 * 主题页面显示
 * 发布区页面
 */
function AiTheme() {
    var $themeContainer = $(".theme-container");
    var $themeName = $themeContainer.find(".theme-info .tempo-strap-header-title");
    var $themeTree = $themeContainer.find('.tempo-theme-private-tree');
    var $refreshBtn = $themeContainer.find('.refresh-btn');
    var $searchBar = $themeContainer.find("#tempo-theme-search-bar");
    var $themeToolbar = $themeContainer.find(".tempo-strap-header");
    var $editBtn = $themeContainer.find('.edit-btn');
    var $sort = $themeContainer.find('#ai_theme_sort');
    var $themeTabs = $themeContainer.find(".tempo-strap-panel-tabs");
    var $pubSearchBar = $themeContainer.find("#tempo-theme-public-search-bar");
    var $pubThemeTree = $themeContainer.find('.tempo-theme-public-tree'); // 发布区
    //发布区灰度服务
    var isCGGLY = $themeContainer.attr("_isCGGLY") == "1";
    var isSJRY = $themeContainer.attr("_isSJRY") == "1";
    var currentUserId = $themeContainer.attr("_currentUserId");
    var fType = $themeContainer.attr("ftype");
    var workSpaceId = $themeContainer.attr("workSpaceId");
    var $templateSearch = $('.tempo-template-search');
    var searchWord = null;
    var theme = this;
    var curFolderId = null;
    var curPFolderId = null;
    var $treeSortPanel = $('#tempo-tree-sort');
    var $pubTreeSortPanel = $('#tempo-app-tree-sort');
    var themeTreeSort = 'DEFAULT';
    var themePubTreeSort = 'DEFAULT';
    var $themeBoard = $themeContainer.find(".theme-board");
    var linkPublishId = null;
    var $noaccess = $themeContainer.find("#noaccess");
    // 设计空间-右侧页面
    var $rightdesignView = $themeContainer.find("#tempo-ai-theme-index-view-right-container");
    var $rightTaskView = $themeContainer.find("#tempo-ai-task-index-view-right-container");
    // 发布空间-右侧页面
    var $rightappView = $themeContainer.find("#tempo-ai-app-index-view-right-container");
    //灰度服务-右侧页面
    var $rightGrayView = $themeContainer.find("#tempo-ai-app-index-view-right-container-gray");
    // 创建任务
    var $createTaskBtn = $themeContainer.find('.create-task-btn');
    // 删除任务
    var $deleteTaskBtn = $themeContainer.find('.delete-task-btn');
    // 分享成果
    var $shareBtn = $themeContainer.find('.share-achivement-btn');
    // 调整目录
    var $selectBtn = $themeContainer.find('.select_target-btn');
    // 更多操作
    var $optsBtn = $themeContainer.find('.achivement-opts-btn');
    // AI关联BI图标
    var $aiRelationBi = $themeContainer.find(".tempo-ai-relation-tempo-bi-icon");

    var $tableName = $('#tempo-header-themName');
    var $updateNameBtn = $('#tempo-header-updatename-btn');
    var index = 0;
    // 应用路径
    var $sharePath = $themeContainer.find('.tempo-app-share-directory');
    var isShowShareDirectory = false;
    //灰度服务分享标识 true为已分享 false为未分享
    var grayShareFlag = true;
    //灰度服务挂载的同步服务父ID
    var syncParentGrayId = "";

    //公共案例/私有案例标记
    var templateFlag = "";
    //全部标签
    var tagList = {};
    //标签筛选框
    var tagId = '';
    //点击加载更多第几页
    var templateCurrentPage = 0;

    var flagEventbus = true;

    var flagEventbusAdd = true;
    //灰度发布弹框
    var dialog = $("<div/>", {
        'id': 'grey-dialog'
    });

    /**
     * 新建灰度发布点击事件
     */
    var creatGray = function () {
        dialog.dialog({
            width: 700,
            height: 570,
            title: TempoUtils.locale("aidsview.gray_service"),
            modal: true,
            resizable: false,
            closeOnEscape: true,
            open: function () {
                $m.loadPage(contextPath + "/api/ai/sysconfig/casebase/view/create-gray", dialog, "");
            },
            close: function () {
                dialog.empty();
                dialog.dialog("destroy").remove();
            },
            buttons: [{
                text: TempoUtils.locale("sysheader.queding"),
                id: 'tempo-queue-add-btn',
                click: function () {
                    window.createGrayVue.$refs["grayConfigRef1"].validate(function (valid) {
                        if (!valid) {
                            return;
                        }
                        console.log(JSON.stringify(window.createGrayVue.grayConfigForm1));
                        var progressbar = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: contextPath + '/api/ai/mine/gray/create-gray-service',
                            method: 'POST',
                            dataType: 'json',
                            data: {
                                id: TempoUtils.uuid(),
                                name: window.createGrayVue.grayConfigForm1.name,
                                serviceAddr: window.createGrayVue.grayConfigForm1.serviceAddr,
                                serviceName1: window.createGrayVue.grayConfigForm1.serviceName1[window.createGrayVue.grayConfigForm1.serviceName1.length - 1],
                                serviceName2: window.createGrayVue.grayConfigForm1.serviceName2[window.createGrayVue.grayConfigForm1.serviceName2.length - 1],
                                publishType: window.createGrayVue.grayConfigForm1.publishType,
                                serviceValue1: window.createGrayVue.grayConfigForm1.serviceValue1,
                                serviceValue2: window.createGrayVue.grayConfigForm1.serviceValue2,
                                selectValue: window.createGrayVue.grayConfigForm1.selectValue,
                                workSpaceId: workSpaceId
                            },
                            success: function (data) {
                                progressbar.tempoprogressbar("destroy");
                                if (data.success) {
                                    failTip(data.message);
                                    $pubThemeTree.gtree('reload');
                                } else {
                                    failTip(data.message);
                                }
                            },
                            error: function () {
                                progressbar.tempoprogressbar("destroy");
                            }
                        });
                        dialog.empty();
                        dialog.dialog("destroy").remove();
                    });
                }
            }, {
                text: TempoUtils.locale("sysheader.quxiao"),
                id: 'tempo-queue-cancel-btn',
                click: function () {
                    dialog.empty();
                    dialog.dialog("destroy").remove();
                }
            }]
        });
    }

    var layout = function () {
        $themeContainer.layout({
            west: {
                size: 227,
                resizable: false,
                spacing_open: 0,
                closable: false
            }
        });
        $themeBoard.layout({
            north: {
                size: 90,
                resizable: false,
                spacing_open: 0,
                closable: false
            }
        });
    }

    var renameThemeUtils = {
        specialCharValidNotBracket: function (text) {
            var regexValid = /^[^~!@#\s\$%\^&\*\+\[\]\|\}\{\\;':,\/<>\?`]+$/;
            if (!regexValid.test(text)) {
                return false;
            }
            return true;
        }
    }

    var bindUpdateNameButton = function () {
        $updateNameBtn.unbind('click').bind('click', function (e) {
            $updateNameBtn.hide();
            var currentName = $tableName.text();
            $tableName.empty();
            var targetInput = $("<input/>", {
                value: currentName,
                "class": 'tempo-mine-theme-name-input'
            }).appendTo($tableName)

            targetInput.validatebox({
                tip: TempoUtils.locale("aidsview.nameValid"),
                required: true,
                maxLength: 60,
                autofill: false
            })
            var desc = $("#theme-description").attr("title");
            targetInput.on("blur", function (e) {
                e.stopPropagation();
                if ($(this).hasClass('validator-invalid')) {
                    return;
                }
                var newValue = $(this).val();
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/rename',
                    method: 'POST',
                    data: {
                        id: theme.id,
                        name: newValue,
                        workSpaceId: workSpaceId,
                        description: desc,
                    },
                    success: function (result) {
                        if (result.success) {
                            if (!$.getters("success", result)) {
                                failTip(result.message);
                                // $updateNameBtn.show();
                                return;
                            }
                            theme.name = newValue;
                            $themeTree.gtree("updateItemName", theme.id, newValue);
                            $themeName.text(newValue).attr('title', newValue);
                            $updateNameBtn.show();
                        } else {
                            $("<div/>").alert({
                                msg: result.message
                            });
                        }
                    }
                })

            }).on("keydown", function (event) {
                if (event.keyCode == 13) {
                    $(this).trigger('blur');
                }
            }).focus();

        });
    }

    var showSharePath = function (appid) {
        var resize = function () {
            if (window.innerWidth < 1150 || !isShowShareDirectory) {
                $sharePath.hide();
            } else {
                $sharePath.show();
            }
        }
        isShowShareDirectory = true;
        $(window).resize(function () {
            resize();
        });
        resize();
        $.ajax({
            url: contextPath + '/api/ai/app/category/path/get?t=' + TempoUtils.uuid(),
            method: 'GET',
            data: {
                id: appid
            },
            success: function (rs) {
                if (rs.success) {
                    if (rs.data) {
                        $("#share_directory").html(rs.data.path);
                        $("#share_directory").attr({
                            "title": rs.data.path,
                            "pid": rs.data.id,
                            "folderid": rs.data.parentId
                        })
                    }
                }
            }
        });
    }

    var toolbar = function () {
        $('.edit-btn').button({
            click: function (e) {
                if (theme.id) {
                    editTheme({id: theme.id, name: theme.name});
                }
            }
        });
        $('.share-btn').button({
            click: function (e) {
                if (theme.id) {
                    openShareView({
                        subjectId: theme.id,
                        workSpaceId: workSpaceId,
                        workSpaceType: $themeContainer.attr("workspacetype")
                    })
                }
            }
        });

        $(".tempo-theme-share-div").on("click", function () {
            if (theme.id) {
                openShareView({
                    subjectId: theme.id,
                    workSpaceId: workSpaceId,
                    workSpaceType: $themeContainer.attr("workspacetype")
                })
            }
        });


        $('.publish-btn').button({
            click: function (e) {
                if (theme.id) {
                    openPublishView({id: theme.id})
                }
            }
        });

        $refreshBtn.button({
            click: function (e) {
                var selectedData = null;
                if ($themeTabs.find(".tempo-strap-panel-tabs-selected").attr("_href") == "#tempo-theme-public-ai") {
                    selectedData = $pubThemeTree.gtree("getSelected");
                    openTheme(selectedData, "pub");
                } else {
                    selectedData = $themeTree.gtree("getSelected");
                    openTheme(selectedData);
                }
                return false;
            }
        });
        Eventbus.bind('preview.theme', openThemePreview);
        addThemeToobarSelectClass($('.edit-btn'));

        // 应用相关
        $createTaskBtn.button({
            emphasize: true,
            click: function (e) {
                var selectedData = $pubThemeTree.gtree("getSelected");
                createTask(selectedData);
            }
        });
        $deleteTaskBtn.button({
            emphasize: true,
            click: function (e) {
                var selectedData = $pubThemeTree.gtree("getSelected");
                deleteTask(selectedData);
            }
        });
        $shareBtn.button({
            emphasize: true,
            click: function (e) {
                if ($rightappView.hasClass("tempo-ai-huidu")) {
                    //灰度服务下同步服务
                    var selectedDataGray = $pubThemeTree.gtree("getSelected");
                    shareApp(selectedDataGray);
                } else if ($rightGrayView.hasClass("tempo-ai-huidu")) {
                    var selectedDataGray = $pubThemeTree.gtree("getSelected");
                    shareApp(selectedDataGray);
                } else {
                    var selectedData = $pubThemeTree.gtree("getSelected");
                    shareApp(selectedData);
                }
            }
        });
        $selectBtn.button({
            emphasize: true,
            click: function (e) {
                var selectedData = $pubThemeTree.gtree("getSelected");
                var data = $pubThemeTree.gtree("getSelected");
                var folderid = $("#share_directory").attr("folderid");
                var pid = $("#share_directory").attr("pid");
                var ca = {
                    "folderid": folderid,
                    "pid": pid
                }
                // appSelectTarget(selectedData,ca)
                if ($rightappView.hasClass("tempo-ai-huidu")) {
                    //灰度服务下同步服务
                    var selectedDataGray = $pubThemeTree.gtree("getSelected");
                    appSelectTarget(selectedDataGray, ca)
                } else if ($rightGrayView.hasClass("tempo-ai-huidu")) {
                    var selectedDataGray = $pubThemeTree.gtree("getSelected");
                    appSelectTarget(selectedDataGray, ca)
                } else {
                    var selectedData = $pubThemeTree.gtree("getSelected");
                    appSelectTarget(selectedData, ca)
                }
            }
        });

        $("#share_directory").on("click", function () {
            var folderid = $(this).attr("folderid");
            var pid = $(this).attr("pid");
            var ca = {
                "folderid": folderid,
                "pid": pid
            }
            var selectedData = $pubThemeTree.gtree("getSelected");
            appSelectTarget(selectedData, ca)
        })

        $optsBtn.button({
            emphasize: true,
            click: function (e) {
            }
        });

        $optsBtn.on("mouseover", function () {
            $("#tempo-header-achivement-opts-infos").show();
            $("#tempo-header-achivement-opts-infos-gray").show();
            var selectedData = $pubThemeTree.gtree("getSelected");
            if ($rightappView.hasClass("tempo-ai-huidu")) {
                if ("sync" == selectedData.type && 'true' == window.showDockerServer) {
                    // 显示镜像推送按钮
                    $("#tempo-docker-image-service-btn").show();
                } else {
                    // 隐藏镜像推送按钮
                    $("#tempo-docker-image-service-btn").hide();
                }
                // 取消分享按钮
                if ("PRIV" == selectedData.modeltype) {
                    $("#tempo-header-achivement-opts-unshare").hide();
                } else {
                    $("#tempo-header-achivement-opts-unshare").show();
                }
            } else {
                if (selectedData != null) {
                    if ("sync" == selectedData.type && 'true' == window.showDockerServer) {
                        // 显示镜像推送按钮
                        $("#tempo-docker-image-service-btn").show();
                    } else {
                        // 隐藏镜像推送按钮
                        $("#tempo-docker-image-service-btn").hide();
                    }
                    // 取消分享按钮
                    if ("PRIV" == selectedData.modeltype) {
                        $("#tempo-header-achivement-opts-unshare").hide();
                    } else {
                        $("#tempo-header-achivement-opts-unshare").show();
                    }
                    if (!grayShareFlag) {
                        $("#tempo-header-achivement-opts-unshare-gray").hide();
                    } else {
                        $("#tempo-header-achivement-opts-unshare-gray").show();
                    }
                }
            }
        })
        $optsBtn.on("mouseout", function () {
            $("#tempo-header-achivement-opts-infos").hide();
            $("#tempo-header-achivement-opts-infos-gray").hide();
        })
        //更多按钮
        $("#tempo-header-achivement-opts-infos").on("mouseover", function () {
            $("#tempo-header-achivement-opts-infos").show();
            var selectedData = $pubThemeTree.gtree("getSelected");
            // var selectedGrayData = $pubGrayTree.gtree("getSelected");
            //判断灰度服务类型
            if ($rightappView.hasClass("tempo-ai-huidu")) {
                //是否分享成果
                if ("PRIV" == selectedData.modeltype) {
                    $("#tempo-header-achivement-opts-unshare").hide();
                } else {
                    $("#tempo-header-achivement-opts-unshare").show();
                }
            } else {
                if ("PRIV" == selectedData.modeltype) {
                    $("#tempo-header-achivement-opts-unshare").hide();
                } else {
                    $("#tempo-header-achivement-opts-unshare").show();
                }
            }
        });
        $("#tempo-header-achivement-opts-infos").on("mouseout", function () {
            $("#tempo-header-achivement-opts-infos").hide();
        });
        //灰度服务更多按钮
        $("#tempo-header-achivement-opts-infos-gray").on("mouseover", function () {
            $("#tempo-header-achivement-opts-infos-gray").show();
            //是否分享成果
            if (!grayShareFlag) {
                $("#tempo-header-achivement-opts-unshare-gray").hide();
            } else {
                $("#tempo-header-achivement-opts-unshare-gray").show();
            }
        });
        $("#tempo-header-achivement-opts-infos-gray").on("mouseout", function () {
            $("#tempo-header-achivement-opts-infos-gray").hide();
        });


        /**
         * 添加镜像推送按钮的点击事件
         */
        $("#tempo-docker-image-service-btn").unbind('click').bind('click', function (event) {
            var dialog = $('<div>').dialog({
                width: 600,
                // height: 800,
                title: TempoUtils.locale("aidsview.docker_image_service_btn"),
                modal: true,
                open: function () {
                    openDockerServiceDialog(this);
                },
                close: function () {
                    clearInterval(dialog.timer);
                    dialog.timer = null;
                    dialog.dialog("destroy").remove();
                },
                buttons: [
                    {
                        text: TempoUtils.locale("aidsview.docker_image_create_push"),
                        id: "tempo-docker-image-service-create-push",
                        click: function () {
                            // 获取服务名，创建人，镜像名称，镜像版本，镜像描述参数
                            var dockerBuildParam = {
                                id: dialog.find(".tempo-flow-id").html(),
                                resourceid: dialog.find(".tempo-resource-id").html(),
                                serviceName: dialog.find(".tempo-service-name").html(),
                                imageCreator: dialog.find(".tempo-docker-image-creator-name").html(),
                                imageName: dialog.find('select[name="tempo-docker-image-name"]').selectmenu("getValue"),
                                imageVersion: dialog.find(".tempo-docker-image-version").html(),
                                imageDesc: dialog.find(".tempo-docker-image-desc").val(),
                            };
                            // 校验镜像名称和镜像描述
                            if (dockerBuildParam.imageName == null || dockerBuildParam.imageName.trim() == "" ||
                                dockerBuildParam.imageDesc == null || dockerBuildParam.imageDesc.trim() == "" || dockerBuildParam.imageDesc.length > 500) {
                                $("<div/>").alert({
                                    msg: TempoUtils.locale("aidsview.docker_null_name_or_verison"),
                                    title: TempoUtils.locale("mine.prompt")
                                });
                                return false;
                            }

                            // 启用 确认 按钮
                            dialog.parent().find('#tempo-docker-image-service-ok').removeClass('ui-state-disabled')
                                .removeClass('ui-widget tempo-button-disabled')
                                .addClass('ui-widget');

                            // 禁用 构建&推送 按钮
                            dialog.parent().find('#tempo-docker-image-service-create-push').removeClass('ui-widget')
                                .addClass('ui-widget tempo-button-disabled')
                                .addClass('ui-state-disabled');

                            // 禁用下拉框
                            dialog.find('select[name="tempo-docker-image-name"]').selectmenu("option", "disabled", true);
                            // 禁用文本栏
                            dialog.find(".tempo-docker-image-desc").attr("disabled", "disabled");
                            // 显示进度和日志框
                            dialog.find(".tempo-docker-image-build-progress-bar").show();
                            dialog.find(".tempo-docker-image-build-log").show();

                            // 生成唯一的表id
                            var dockerTableId = TempoUtils.uuid();
                            // 保存流程信息 异步
                            saveFlowInfo(dockerTableId, dockerBuildParam);
                            // 开始构建docker镜像 异步
                            startBuildDockerImage(dialog, dockerTableId, dockerBuildParam);
                        }
                    },
                    {
                        text: TempoUtils.locale("aidsview.theme_sure"),
                        id: "tempo-docker-image-service-ok",
                        click: function () {
                            dialog.dialog("close");
                        }
                    }
                ]
            });
            // 调整配置弹框位置
            dialog.parent().css("top", "15%");
            // 禁用 确认 按钮
            dialog.parent().find('#tempo-docker-image-service-ok').removeClass('ui-widget')
                .addClass('ui-widget tempo-button-disabled')
                .addClass('ui-state-disabled');
        });

        /**
         * 获取流程信息
         * @param dockerTableId 表id
         * @param dockerBuildParam docker构建参数
         */
        var saveFlowInfo = function (dockerTableId, dockerBuildParam) {
            $.ajax({
                type: "POST",
                // 构建docker镜像
                url: contextPath + "/api/ai/app/docker/update-image-info",
                data: {
                    dockerTableId: dockerTableId,
                    serviceId: dockerBuildParam.id,
                },
                async: false,
                success: function (response) {
                },
                error: function (data) {
                    // 给出提示信息
                    $("<div/>").alert({
                        msg: data.responseJSON.message,
                        title: TempoUtils.locale("mine.prompt")
                    });
                }
            });
        }

        /**
         * 构建docker的方法
         * @param dialog 弹框对象
         * @param dockerTableId 表id
         * @param dockerBuildParam docker构建参数
         */
        var startBuildDockerImage = function (dialog, dockerTableId, dockerBuildParam) {
            $.ajax({
                type: "POST",
                // 构建docker镜像
                url: contextPath + "/api/ai/app/docker/build-docker-image",
                data: {
                    dockerTableId: dockerTableId,
                    id: dockerBuildParam.id,
                    imageCreator: dockerBuildParam.imageCreator,
                    imageName: dockerBuildParam.imageName,
                    imageVersion: dockerBuildParam.imageVersion,
                    imageDesc: dockerBuildParam.imageDesc,
                    serviceName: dockerBuildParam.serviceName
                },
                success: function (response) {
                    if (response && !response.success) {
                        $("<div/>").alert({
                            msg: response.message,
                            title: TempoUtils.locale("mine.prompt")
                        });
                    }
                    // 将进度条改变颜色
                    dialog.find(".image-one-gray").addClass("image-one-blue").removeClass("image-one-gray");
                    // dialog.find(".line-one").css("background", "#337BFF");
                    // 定时查询日志
                    dialog.timer = setInterval(function () {
                        $.ajax({
                            type: "GET",
                            // 获取构建docker镜像日志
                            url: contextPath + "/api/ai/app/docker/get-build-image-log?dockerTableId=" + dockerTableId,
                            success: function (response) {
                                if (response && response.success && response.data && response.data.imageBuildLog) {
                                    // 处理一下日志格式
                                    var log = formatLog(response.data.imageBuildLog);
                                    dialog.find(".tempo-docker-image-build-log pre").text(log);
                                    // 判断构建是否成功
                                    var buildSuccessSign = "Successfully tagged " + dockerBuildParam.imageName + ":" + dockerBuildParam.imageVersion;
                                    if (log.indexOf(buildSuccessSign) != -1) {
                                        dialog.find(".line-one").css("background", "#337BFF");
                                        dialog.find(".image-two-gray").addClass("image-two-blue").removeClass("image-two-gray");
                                    }
                                    // 判断推送是否成功
                                    var pushSuccessSignOne = dockerBuildParam.imageVersion + ": digest";
                                    var pushSuccessSignTwo = "size:";
                                    if (log.indexOf(pushSuccessSignOne) != -1 && log.indexOf(pushSuccessSignTwo) != -1) {
                                        dialog.find(".line-two").css("background", "#337BFF");
                                        dialog.find(".image-three-gray").addClass("image-three-blue").removeClass("image-three-gray");
                                    }
                                }
                            }
                        });
                    }, 3000);

                },
                error: function (data) {
                    // 给出提示信息
                    $("<div/>").alert({
                        msg: data.responseJSON.message,
                        title: TempoUtils.locale("mine.prompt")
                    });
                }
            });

        };

        /**
         * 格式化日志  将↵ ↵↵ ↵↵↵ 转化为 \n
         * @param log 需要格式化的日志
         */
        var formatLog = function (log) {
            log = log.replace(/↵↵↵/g, "\n");
            log = log.replace(/↵↵/g, "\n");
            log = log.replace(/↵/g, "\n");
            return log;
        };

        /**
         * 初始化镜像服务配置页面
         * @param dialog 镜像服务配置页面div
         */
        var openDockerServiceDialog = function (dialog) {
            var dockerImageNameDiv = $('<div>').addClass("tempo-docker-service-config-dialog").appendTo(dialog);
            // 流程信息
            var flowInfo = $pubThemeTree.gtree("getSelected");
            initDockerServicePage(dockerImageNameDiv, flowInfo);
            // 表名称 pf_tempo_docker_image_service
            //   表id             流程id         镜像名称    版本号    服务名称（服务配置里的） 镜像描述  创建人         创建时间    状态(0成功1失败2准备构建3构建中)   构建文件路径        构建日志          服务ID         应用名称         空间名称        备注
            // docker_data_id     flow_id     image_name  image_version  service_name   image_desc  image_creator  image_create_time          status    build_image_folder_path   image_build_log     service_id  applicationName  workspaceName    remark
            //     string         String         string      int           string          string      string          long                  int                string               string            string        string         string           string

            // 初始化下拉框和版本号，并做联动
            $.ajax({
                type: "GET",
                // 获取去重后的镜像名
                url: contextPath + "/api/ai/app/docker/get-image-name",
                async: false,
                success: function (response) {
                    if (response && !response.success) {
                        $("<div/>").alert({
                            msg: response.message,
                            title: TempoUtils.locale("mine.prompt")
                        });
                    }
                    var imageNameSelect = dockerImageNameDiv.find('select[name="tempo-docker-image-name"]');
                    if (response.data) {
                        // 添加下拉选项
                        var dockerImageNameList = response.data;
                        var dockerImageNameListLen = dockerImageNameList.length;
                        for (var i = 0; i < dockerImageNameListLen; i++) {
                            $("<option>").val(dockerImageNameList[i].IMAGE_NAME)
                                .html(dockerImageNameList[i].IMAGE_NAME)
                                .appendTo(imageNameSelect);
                        }
                        // 初始化下拉框
                        imageNameSelect.selectmenu({
                            width: 150,
                            height: 26,
                            editable: true,
                            // searchable: true,
                            selectFirst: false,
                            labelForTitle: true,
                            validateLabel: function (newValue) {
                                dockerImageNameDiv.find(".tempo-docker-image-version").html("V1");
                                return newValue;
                            },
                            change: function (enent, item) {
                                var imageName = dockerImageNameDiv.find('select[name="tempo-docker-image-name"]').selectmenu("getValue");
                                // 初始化版本号
                                $.ajax({
                                    type: "GET",
                                    // 获取最大的版本号
                                    url: contextPath + "/api/ai/app/docker/get-max-image-version?imageName=" + imageName,
                                    async: false,
                                    success: function (response) {
                                        if (response && !response.success) {
                                            $("<div/>").alert({
                                                msg: response.message,
                                                title: TempoUtils.locale("mine.prompt")
                                            });
                                        }
                                        if (response.data) {
                                            var newVersion = 1;
                                            if (response.data[0].IMAGE_VERSION) {
                                                newVersion = parseInt(response.data[0].IMAGE_VERSION) + 1;
                                            }
                                            dockerImageNameDiv.find(".tempo-docker-image-version").html("V" + newVersion);
                                        }
                                    },
                                    error: function (data) {
                                        $("<div/>").alert({
                                            msg: data.responseJSON.message,
                                            title: TempoUtils.locale("mine.prompt")
                                        });
                                    }
                                });
                            }
                        });
                    }
                },
                error: function (data) {
                    $("<div/>").alert({
                        msg: data.responseJSON.message,
                        title: TempoUtils.locale("mine.prompt")
                    });
                }
            });


        };

        /**
         * 初始化镜像服务页面
         * @param dockerImageNameDiv 父div <div><div style="display:none"></div></div>
         */
        var initDockerServicePage = function (dockerImageNameDiv, flowInfo) {
            $('<div>\n' +
                '                <div class="tempo-docker-image-padding">\n' +
                '                <div style="display:none">' +
                '					 <span class="tempo-flow-id">' + flowInfo.id + '</span>' +
                '                </div>' +
                '                <div style="display:none">' +
                '					 <span class="tempo-resource-id">' + flowInfo.resourceid + '</span>' +
                '                </div>' +
                '                <div style="display:none">' +
                '					 <span class="tempo-service-name">' + flowInfo.name + '</span>' +
                '                </div>' +
                '                <div style="display:none">' +
                '					 <span class="tempo-docker-image-creator-name">' + flowInfo.userName + '</span>' +
                '                </div>' +
                '                <div>\n' +
                '                <div class="tempo-docker-image-text-align">\n' +
                '                    <label>' + TempoUtils.locale("aidsview.docker_image_name") + '</label>\n' +
                '                </div>' +
                '                    <select name="tempo-docker-image-name">\n' +
                '                    </select>\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                <div class="tempo-docker-image-text-align">\n' +
                '                    <label>' + TempoUtils.locale("aidsview.docker_image_version") + '</label>\n' +
                '                </div>' +
                '                    <label class="tempo-docker-image-version">V1</label>\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                <div class="tempo-docker-image-text-align">\n' +
                '                    <label class="tempo-docker-image-padding-top">' + TempoUtils.locale("aidsview.docker_image_desc") + '</label>\n' +
                '                </div>' +
                '                    <textarea class="tempo-docker-image-desc" placeholder="' + TempoUtils.locale("aidsview.docker_image_desc_tip") + '"/></textarea>\n' +
                '                </div>\n' +
                '                </div>' +
                '                <div class="tempo-docker-image-build-progress-bar" style="display: none">\n' +
                '                    <!--  标题进度条 start-->\n' +
                '                    <div>\n' +
                '                        <div class="process-bar">\n' +
                '    					 	 <div class="image-one-gray"></div>' +
                '                            <div class="line-one line" ></div>\n' +
                '                        </div>\n' +
                '                    	 <div class="process-bar">' +
                '    						<div class="image-two-gray"></div>' +
                '  					 		<div class="line-two line"></div>\n' +
                '    					 </div>\n' +
                '    					 <div class="process-bar-end">\n' +
                '    						<div class="image-three-gray"></div>' +
                '    					 </div>\n' +
                '    			 	 </div>\n' +
                '    			 </div>\n' +
                '                <div class="tempo-docker-image-build-log" style="display: none">\n' +
                '                    <pre></pre>\n' +
                '                </div>\n' +
                '            </div>').appendTo(dockerImageNameDiv);
        };

        // 取消发布
        $("#tempo-header-achivement-opts-unpublish").on("click", function (e) {
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: TempoUtils.locale("aidsview.app_cancel_publish_confirm"),
                ok: function () {
                    if ($rightappView.hasClass("tempo-ai-huidu")) {
                        failTip(TempoUtils.locale("aidsview.gray_service_sync"));
                    } else {
                        var objid = $rightappView.attr("objid");
                        var flowid = $rightappView.attr("flowid");
                        var progressbar = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: contextPath + "/api/ai/app/unpublish",
                            data: {
                                id: flowid,
                                flowObjectId: objid
                            },
                            dataType: 'json',
                            type: 'post',
                            traditional: true,
                            success: function (result) {
                                progressbar.tempoprogressbar("destroy");
                                if (result && result.success) {
                                    failTip(TempoUtils.locale("aidsview.app_unpublish_success"));
                                    $pubThemeTree.gtree('reload');
                                    showWelcome("publish");
                                } else {
                                    if (result.message === "gray") {
                                        failTip(TempoUtils.locale("aidsview.gray_service_sync"));
                                    } else {
                                        failTip(result.message);
                                    }
                                }
                            },
                            error: function (result) {
                                progressbar.tempoprogressbar("destroy");
                            },
                            complete: function () {
                                $("#tempo-header-achivement-opts-infos").hide();
                            }
                        });
                    }
                }
            });
        })

        // 取消发布
        $("#tempo-header-achivement-opts-unpublish-gray").on("click", function (e) {
            $("<div>").confirm({
                width: 500,
                height: 197,
                msg: TempoUtils.locale("aidsview.app_cancel_publish_confirm"),
                ok: function () {
                    var objid = $rightGrayView.attr("objid");
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/mine/gray/unpublish",
                        data: {
                            id: objid,
                        },
                        dataType: 'json',
                        type: 'post',
                        traditional: true,
                        success: function (result) {
                            progressbar.tempoprogressbar("destroy");
                            if (result && result.success) {
                                failTip(TempoUtils.locale("aidsview.app_unpublish_success"));
                                $pubThemeTree.gtree('reload');
                                showWelcome("publish");
                            } else {
                                failTip(result.message);
                            }
                        },
                        error: function (result) {
                            progressbar.tempoprogressbar("destroy");
                        },
                        complete: function () {
                            $("#tempo-header-achivement-opts-infos").hide();
                        }
                    });
                }
            });
        })
        // 取消分享
        $("#tempo-header-achivement-opts-unshare").on("click", function () {
            if ($rightappView.hasClass("tempo-ai-huidu")) {
                //灰度服务下同步服务
                var selectedDataGray = $pubThemeTree.gtree("getSelected");
                unshareApp(selectedDataGray);
            } else {
                var selectedData = $pubThemeTree.gtree("getSelected");
                unshareApp(selectedData);
            }
        })
        //取消灰度服务分享
        $("#tempo-header-achivement-opts-unshare-gray").on("click", function () {
            if ($rightGrayView.hasClass("tempo-ai-huidu")) {
                var selectedDataGray = $pubThemeTree.gtree("getSelected");
                unshareApp(selectedDataGray);
            }
        });
        //返回工作空间管理界面
        $("#tempo-go-back-workspace").click(function () {
            var thisUrl = contextPath + "/api/ai/resource/view/workspace?enterType=theme";
            thisUrl = TempoUtils.addHideIconParam(thisUrl);
            window.location.href = thisUrl;
        })
    }

    var beforeMenuShow = function (data, level) {
        var workspacetype = $('.theme-container').attr('workspacetype');
        if (data && data.fileType == 'FOLDER') {
            if (data.id == "share") {
                return;
            }
            var menu = ['createFolder', 'createTheme', 'importTheme', "renameFolder", 'deleteFolder'];
            if (data.id == "-1") {
                // 根节点不能重命名
                menu.splice(3);
                return menu;
            }
            if ((workspacetype == 'self' && level > 1) || (workspacetype == 'public' && level > 0)) {
                menu.splice(0, 1);
                return menu;
            }
            return menu;
        } else if (data && data.fileType == 'FILE') {
            if (workspacetype == 'self') {
                if (data.belong == "1") {
                    // 我的应用
                    return ['edit', 'copyTo', 'export', 'move', 'delete', 'rename'];
                } else {
                    // 邀请我的
                    return ['edit', 'copyTo', 'export', 'remove'];
                }
            }
            return ['edit', 'copyTo', 'export', 'move', 'delete', 'rename'];
        } else if (data && data.fileType == 'VIRTUAL_FOLDER') {

        }
    }


    /**
     *发布区
     */
    var pubBeforeMenuShow = function (data, level) {
        var workspacetype = $('.theme-container').attr('workspacetype');
        if (data && data.fileType == 'FILE') {
            if (workspacetype == 'public') {
                // 返回值
                var resource = [];
                // 加载列表
                $.ajax({
                    url: contextPath + ('/api/ai/resource/template/is-publish'),
                    type: 'post',
                    data: {
                        appId: data.id
                    },
                    dataType: 'json',
                    async: false,
                    success: function (rs) {
                        if (rs.data == null) {
                            // 发布为案例
                            resource.push('pubTheme');
                        } else {
                            resource.push('updateTheme');
                        }
                    }
                });
                return resource;

            }
        }
    }
    var getMenus = function () {
        var menus = [{
            text: TempoUtils.locale("aidsview.folder_create2"),
            id: 'createFolder',
        }, {
            text: TempoUtils.locale("aidsview.theme_create"),
            id: 'createTheme',
        }, {
            text: TempoUtils.locale("aidsview.theme_import"),
            id: 'importTheme',
        }, {
            text: TempoUtils.locale("aidsview.RENAME"),
            id: 'renameFolder',
        }, {
            text: TempoUtils.locale("aidsview.DELETE"),
            id: 'deleteFolder',
        }, {
            text: TempoUtils.locale("aidsview.EDIT"),
            id: 'edit',
        }, {
            text: TempoUtils.locale("aidsview.RENAME"),
            id: 'rename',
        }, {
            text: TempoUtils.locale("aidsview.COPY"),
            id: 'copy',
        }, {
            text: TempoUtils.locale("aidsview.COPY"),
            id: 'copyTo',
        }, {
            text: TempoUtils.locale("aidsview.EXPORT"),
            id: 'export',
        }, {
            text: TempoUtils.locale("aidsview.MOVE"),
            id: 'move',
        }, {
            text: TempoUtils.locale("aidsview.DELETE"),
            id: 'delete',
        }, {
            text: TempoUtils.locale("aidsview.remove"),
            id: 'remove',
        }, {
            text: TempoUtils.locale("aidsview.theme_template"),
            id: 'template',
        }, {
            text: TempoUtils.locale("aidsview.pub_theme"),
            id: 'pubTheme',
        }, {
            text: TempoUtils.locale("aidsview.update_theme"),
            id: 'updateTheme',
        }];
        return menus;
    }

    var expandFirst = function () {
        if ($searchBar.searchbar("getValue").trim() == "") {
            $themeTree.gtree("expand", "share");
            $themeTree.gtree("expand", "-1");
        }
    }

    /**
     * 初始化应用树
     */
    var initExplorer = function (rootData) {
        if ($themeTree.hasClass("tempo-gtree")) {
            $themeTree.gtree("destroy");
        }
        var menus = getMenus();
        $themeTree.gtree({
            url: contextPath + '/api/ai/resource/analyse/tree',
            enableSelect: true,
            rootData: rootData,
            beforeRequest: function (data) {
                var param = {};
                if (data.sort == null || data.sort == "") {
                    data.sort = themeTreeSort;
                }
                if (!data || !data.id) {
                    param = {sort: data.sort};
                } else {
                    param = {sort: data.sort, parentId: data.id};
                }
                param.searchWord = data.searchWord || "";
                param.workSpaceId = $('.theme-container').attr("workspaceid");
                return param;
            },
            getItemIcon: function (nodeData) {
                if (nodeData.fileType == 'FILE') {
                    return 'tempo-api-icon-tree-16  tempo-api-icon-tree-16-position-10';
                } else {
                    return 'tempo-ui-icon-api-folder-close';
                }
            },
            onSelect: function (nodeData) {
                var item = $(this);
                var that = $(".tempo-theme-private-tree")
                $updateNameBtn.show();
                treeSelectIconChange(item, that, nodeData)
            },
            isLeafNode: function (nodeData) {
                if (nodeData.fileType == 'FILE') {
                    return true;
                } else {
                    return false;
                }
            },
            nodeButtons: [{
                isShowNodeButtons: function (nodeData) {
                    if (!nodeData || nodeData.id == 'share'
                        || (!nodeData.fileType || nodeData.fileType == 'VIRTUAL_FOLDER')) {
                        return false;
                    }
                    return true;
                },
                isShowGrayButtons: function (nodeData) {
                    return nodeData.fileType === 'hdfw';
                },
                click: function (nodeData, e) {
                    e.stopPropagation();
                    var showMenus = [];
                    var level = $themeTree.gtree("getNodeLevel", nodeData.id);
                    var showMenuIds = beforeMenuShow(nodeData, level);
                    if (!showMenuIds || showMenuIds.length == 0) {
                        return;
                    }
                    for (var i = 0; i < menus.length; i++) {
                        if (showMenuIds.indexOf(menus[i].id) > -1) {
                            showMenus.push(menus[i]);
                        }
                    }
                    if (showMenus.length == 0) {
                        return;
                    }
                    var contextmenu = $("<ul class='tempo-gtree-menu'/>").appendTo($("body")).contextmenu({
                        data: showMenus,
                        select: function (ele, ui) {
                            var data = ui.linkEl.data;
                            var menuId = ui.select.id;
                            switch (menuId) {
                                // 文件夹
                                case "createFolder" :
                                    createFolder(data);
                                    break;
                                case "deleteFolder" :
                                    deleteFolder(data, ele);
                                    break;
                                case "createTheme" :
                                    createTheme(data, ele);
                                    break;
                                case "importTheme" :
                                    importTheme(data, ele);
                                    break;
                                case "renameFolder" :
                                    renameFolder(data, ele);
                                    break;
                                // 主题
                                case "edit" :
                                    editTheme(data);
                                    break;
                                case "copy" :
                                    copyTheme(data, ele);
                                    break;
                                case "export" :
                                    exportTheme(data, ele);
                                    break;
                                case "move" :
                                    moveTheme(data, ele);
                                    break;
                                case "delete" :
                                    deleteTheme(data.id, ele);
                                    break;
                                case "rename" :
                                    renameTheme(data, ele);
                                    break;
                                case "remove" :
                                    removePrivilege(data);
                                    break;
                                case "copyTo" :
                                    copyThemeTo(data, ele);
                                    break;
                            }
                        }
                    });
                    var offset = $(this).offset();
                    var top = offset.top;
                    var menuHeight = contextmenu.outerHeight();
                    if (top + menuHeight > window.innerHeight) {
                        top = top - menuHeight;
                    }
                    contextmenu.contextmenu("show", {
                        position: {
                            left: offset.left + $(this).width() / 2 + 7,
                            top: top
                        },
                        linkEl: {
                            data: nodeData
                        }
                    });
                }
            }],
            onItemClick: function (data) {
                $noaccess.hide();
                $rightappView.parent().show();
                $rightappView.hide();
                $rightGrayView.hide();
                $rightdesignView.show();
                openTheme(data);
                $themeToolbar.show();
            },
            renderComplete: function () {
                expandFirst();
            },
            loadComplete: function (resultData) {
                if (!$.getters("success", resultData)) {
                    $("<div/>").alert({
                        width: alertDialogWidth,
                        height: alertDialogHeight,
                        msg: $.getters("message", resultData) || TempoUtils.locale("aidsview.query_theme_fail")
                    });
                    return [];
                }
                return resultData.data || [];
            }
        });
    };

    var treeSelectIconChange = function (item, that, nodeData) {
        if (that.find(".tempo-icon-select").length > 0) {
            that.find(".tempo-icon-select").removeClass("tempo-ui-icon-api-folder-open-selected tempo-ui-icon-api-folder-close-selected tempo-api-icon-tree-16-position-10-selected tempo-api-icon-tree-16-position-9-selected tempo-ai-api-icon-tree-16-position-8-selected tempo-api-icon-tree-16-position-49-selected tempo-icon-select");
        }
        if (that.find(".tempo-gray-icon").length > 0) {
            that.find(".tempo-gray-icon").removeClass("tempo-api-icon-tree-16-position-gray-select");
            that.find(".tempo-gray").removeClass("tempo-gray-icon-background");
            that.find(".tempo-gray").addClass("tempo-gray-icon-back");
        }
        if (that.find(".tempo-ysfw-icon").length > 0) {
            that.find(".tempo-ysfw-icon").removeClass("tempo-api-icon-tree-16-position-ysfw-select");
            that.find(".tempo-gray").removeClass("tempo-gray-icon-background");
            that.find(".tempo-gray").addClass("tempo-gray-icon-back");
        }
        if (nodeData.fileType) {
            if (nodeData.fileType.toUpperCase() === "YSFW") {
                item.find("span:eq(0)").addClass("tempo-ysfw-icon");
                item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-ysfw-select");
            }
            if (nodeData.fileType.toUpperCase() === "HDFW") {
                that.find(".tempo-gray").removeClass("tempo-gray-icon-back");
                that.find(".tempo-gray").addClass("tempo-gray-icon-background");
                item.find("span:eq(0)").addClass("tempo-gray-icon");
                item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-gray-select");
            }
            if (nodeData.fileType.toUpperCase() == "FOLDER") {
                if (item.find("span:eq(0)").hasClass("tempo-ui-icon-api-folder-close")) {
                    item.find("span:eq(0)").addClass("tempo-icon-select");
                    item.find("span:eq(0)").addClass("tempo-ui-icon-api-folder-open-selected");
                } else {
                    item.find("span:eq(0)").addClass("tempo-icon-select");
                    item.find("span:eq(0)").addClass("tempo-ui-icon-api-folder-close-selected");
                }
            }
            if (nodeData.fileType.toUpperCase() == "FILE" && nodeData.type != "flow" && nodeData.type != "plflow") {
                if (item.find("span:eq(0)").hasClass("tempo-api-icon-16-tree-position-9")) {
                    item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-10-selected");
                    item.find("span:eq(0)").addClass("tempo-icon-select");
                } else {
                    item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-9-selected");
                    item.find("span:eq(0)").addClass("tempo-icon-select");
                }
            }
            ;
            if (nodeData.fileType.toUpperCase() == "FILE" && nodeData.type != "flow" && nodeData.type != "plflow" && nodeData.type != "THEME") {
                item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-10-selected");
                item.find("span:eq(0)").addClass("tempo-icon-select");
            }
        }
        if (nodeData.type == "flow" || nodeData.type == "plflow") {
            item.find("span:eq(0)").addClass("tempo-icon-select");
        }
        //灰度服务流程
        if (nodeData.type == "sync") {
            item.find("span:eq(0)").addClass("tempo-icon-select");
        }
        if (nodeData.type == "task") {
            item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-49-selected");
            item.find("span:eq(0)").addClass("tempo-icon-select");
        }
        if (nodeData.type == "gray") {
            item.find("span:eq(0)").addClass("tempo-gray-icon");
            item.find("span:eq(0)").addClass("tempo-api-icon-tree-16-position-gray-select");
        }
    }

    var initPubTree = function (rootData) {
        if ($pubThemeTree.hasClass("tempo-gtree")) {
            $pubThemeTree.gtree("destroy");
        }
        delete rootData.id;
        var menus = getMenus();
        $pubThemeTree.gtree({
            url: contextPath + '/api/ai/resource/analyse/app-analyse-tree',
            enableSelect: true,
            rootData: rootData,
            idKey: "uuid",
            beforeRequest: function (data) {
                var param = {};
                if (data.sort == null || data.sort == "") {
                    data.sort = themePubTreeSort;
                }
                if (!data || !data.id) {
                    param = {sort: data.sort};
                } else {
                    param = {sort: data.sort, parentId: data.id};
                }
                //parentId-2代表灰度服务，-1代表原生服务
                if ("-2" == data.parentId) {
                    param.hdfw = "true";
                }
                param.appId = data.appId || "";
                param.searchWord = data.searchWord || "";
                param.workSpaceId = $('.theme-container').attr("workspaceid");
                return param;
            },
            getItemIcon: function (nodeData) {
                if (nodeData.type == 'task') {
                    return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-49';
                }
            },
            getFolderCloseIcon: function (nodeData) {
                if (nodeData.fileType == "ysfw") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-ysfw";
                }
                if (nodeData.type == "gray" || nodeData.fileType == "hdfw") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-gray";
                } else if (nodeData.type == "sync") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync";
                }
                if (nodeData.type == "flow" || nodeData.type == "plflow") {
                    if (nodeData.fileType == "stream") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-stream';
                    } else if (nodeData.fileType == "sync") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync';
                    } else if (nodeData.fileType == "async") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-async';
                    }
                } else if (nodeData.type == "THEME") {
                    return "tempo-api-icon-tree-16  tempo-api-icon-tree-16-position-10";
                }
                return "tempo-ui-icon-api-folder-close";
            },
            getFolderOpenIcon: function (nodeData) {
                if (nodeData.fileType == "ysfw") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-ysfw";
                }
                if (nodeData.type == "gray" || nodeData.fileType == "hdfw") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-gray";
                } else if (nodeData.type == "sync") {
                    return "tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync";
                }
                if (nodeData.type == "flow" || nodeData.type == "plflow") {
                    if (nodeData.fileType == "stream") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-stream';
                    } else if (nodeData.fileType == "sync") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-sync';
                    } else if (nodeData.fileType == "async") {
                        return 'tempo-ai-api-icon-tree-16 tempo-api-icon-tree-16-position-async';
                    }
                } else if (nodeData.type == "THEME") {
                    return "tempo-api-icon-tree-16 tempo-api-icon-16-tree-position-9";
                }
                return "tempo-ui-icon-api-folder-open";
            },
            onSelect: function (data) {
                $("#tempo-ai-app-index-view-right-container").attr("objid", data.id);
                var item = $(this);
                var that = $(".tempo-theme-public-tree");
                $updateNameBtn.show();
                treeSelectIconChange(item, that, data);
                var tag = true;
                if (data.type == "flow" || data.type == "plflow") {
                    // 展开页面
                    hideWelcome();
                    hideTemplate();
                    $rightdesignView.hide();
                    $rightTaskView.hide();
                    $rightGrayView.hide();
                    $noaccess.hide();
                    $rightappView.parent().show();
                    $rightappView.show();
                    $rightappView.removeClass("tempo-ai-huidu");
                    $rightGrayView.removeClass("tempo-ai-huidu");
                    $(".tempo-strap-header-right").show();
                    appClickEvent.modifyInfo(data, tag);
                    appClickEvent.loadRigPage(data.id, tag);
                    updateStatusLoop(data.id, null, data.fileType);
                } else if (data.type == "sync") {
                    var flagSync = true;
                    $.ajax({
                        url: contextPath + '/api/ai/mine/gray/get-sync-jurisdiction',
                        type: 'post',
                        data: {
                            workSpaceId: workSpaceId,
                            syncId: data.id,
                            flagChengGuo: "false"
                        },
                        async: false,
                        success: function (result) {
                            if (!result.success) {
                                flagSync = false;
                            }
                        }
                    });
                    // 展开页面
                    hideWelcome();
                    hideTemplate();
                    $rightdesignView.hide();
                    $rightTaskView.hide();
                    $rightGrayView.hide();
                    if (!flagSync) {
                        $rightappView.parent().hide();
                        $noaccess.css("top", "0px");
                        $noaccess.css("left", $($noaccess.parent().children()[0]).width() + "px");
                        $noaccess.css("width", $rightappView.parent().width() + "px");
                        $noaccess.css("height", $rightappView.parent().height() + "px");
                        $noaccess.show();
                        $noaccess.find("iframe").attr("src", contextPath + "/api/ai/mine/gray/view");
                        return;
                    }
                    $rightappView.parent().show();
                    $rightappView.show();
                    $noaccess.hide();
                    $rightappView.addClass("tempo-ai-huidu");
                    $rightGrayView.removeClass("tempo-ai-huidu");
                    $(".tempo-strap-header-right").show();
                    flowClickEvent.modifyInfo(data);
                    flowClickEvent.loadRigPage(data.id, tag);
                    updateStatusLoop(data.id, null, data.type);
                } else if (data.type == "gray") {
                    hideWelcome();
                    $rightdesignView.hide();
                    $rightTaskView.hide();
                    $rightappView.hide();
                    $noaccess.hide();
                    $rightappView.parent().show();
                    $rightGrayView.show();
                    $rightGrayView.addClass("tempo-ai-huidu");
                    $rightappView.removeClass("tempo-ai-huidu");
                    $(".tempo-strap-header-right-gray").show();
                    GrayClickEvent.modifyInfo(data, tag);
                    GrayClickEvent.loadRigPage(data.id, tag);
                } else {
                    $(".tempo-strap-header-right").hide();
                }
            },
            isLeafNode: function (data) {
                if (data.type == "task") {
                    return true;
                } else {
                    return false;
                }
            },
            //发布区应用发布为案例按钮
            nodeButtons: [{
                isShowNodeButtons: function (nodeData) {
                    if (!nodeData || nodeData.id == 'share'
                        || (!nodeData.fileType || nodeData.fileType == 'VIRTUAL_FOLDER' || nodeData.fileType == 'ysfw' /*|| nodeData.fileType == 'hdfw' */ || nodeData.type == 'flow' || nodeData.type == 'plflow' || nodeData.fileType == 'FOLDER' || nodeData.type == "task")) {
                        return false;
                    }
                    return true;
                },
                isShowGrayButtons: function (nodeData) {
                    return nodeData.fileType == 'hdfw';
                },
                click: function (nodeData, e) {
                    if (nodeData.fileType == 'hdfw') {
                        creatGray();
                        return;
                    }
                    e.stopPropagation();
                    var showMenus = [];
                    var level = $pubThemeTree.gtree("getNodeLevel", nodeData.id);
                    var showMenuIds = pubBeforeMenuShow(nodeData, level);
                    if (!showMenuIds || showMenuIds.length == 0) {
                        return;
                    }
                    for (var i = 0; i < menus.length; i++) {
                        if (showMenuIds.indexOf(menus[i].id) > -1) {
                            showMenus.push(menus[i]);
                        }
                    }
                    if (showMenus.length == 0) {
                        return;
                    }
                    var contextmenu = $("<ul class='tempo-gtree-menu'/>").appendTo($("body")).contextmenu({
                        data: showMenus,
                        select: function (ele, ui) {
                            var data = ui.linkEl.data;
                            var menuId = ui.select.id;
                            switch (menuId) {
                                // 文件夹
                                case "pubTheme" :
                                    pubTheme(data);
                                    break;
                                case "updateTheme" :
                                    updateTemplate(data);
                                    break;
                            }
                        }
                    });
                    var offset = $(this).offset();
                    var top = offset.top;
                    var menuHeight = contextmenu.outerHeight();
                    if (top + menuHeight > window.innerHeight) {
                        top = top - menuHeight;
                    }
                    contextmenu.contextmenu("show", {
                        position: {
                            left: offset.left + $(this).width() / 2 + 7,
                            top: top
                        },
                        linkEl: {
                            data: nodeData
                        }
                    });
                }
            }],
            onItemClick: function (data) {
                $('.welcome-page').hide();
                if (data.type == "flow" || data.type == "plflow") {
                    hideWelcome();
                    hideTemplate();
                    $rightdesignView.hide();
                    $rightTaskView.hide();
                    $rightappView.show();
                    $rightappView.removeClass("tempo-ai-huidu");
                    $(".tempo-strap-header-right").show();
                    var tag = true;
                    appClickEvent.modifyInfo(data, tag);
                    appClickEvent.loadRigPage(data.id, tag);
                } else {
                    $rightdesignView.hide();
                    $rightappView.find('.tempo-ai-app-rightzone-bot-service').empty();
                    $rightappView.hide();
                    $rightTaskView.show();
                    // 隐藏灰度服务页面
                    $rightGrayView.hide();
                    $(".tempo-strap-header-right").show();
                    // 加载任务页面
                    modifyInfo(data);
                    loadTaskRightPage(data);
                }
                updateStatusLoop(data.id, null, data.fileType);
            },
            renderComplete: function () {
                if (linkPublishId) {
                    $pubThemeTree.gtree("expand", linkPublishId);
                } else {
                    $pubThemeTree.gtree("expand", "-1");
                }
            }
        });
    };

    var appClickEvent = {
        modifyInfo: function (data, tag) {
            $('.tempo-ai-app-rightzone-top span[id="ca-name"]').text(data.name).attr('title', data.name);
            //添加同步服务标识
            var span = $($('.tempo-ai-app-rightzone-top span[id="ca-name"]')[0]);
            span.next().remove();
            if (data.type == "plflow") {
                var width = span.width();
                var plImg = $("<img/>").addClass("tempo-sync-service-pl-image");
                span.after(plImg);
                plImg.attr("src", contextPath + "/css/images/pl_icon.png");
                if (width >= 420) {
                    plImg.css("margin-left", "-15px").css("margin-top", "-28px");
                } else {
                    plImg.css("margin-left", "5px").css("margin-top", "-28px");
                }
            }
            $('.tempo-ai-app-rightzone-top span[id="ca-creator"]').text(data.userName).attr("title", data.userName);
            $.ajax({
                url: contextPath + '/api/ai/mineresource/getThemeNameByCategoryId',
                method: 'POST',
                data: {
                    id: data.id
                },
                success: function (themeName) {
                    $('.tempo-ai-app-rightzone-top span[id="belong_theme"]').text(themeName).attr('title', themeName);
                }
            })
            var ctype = "";
            var status = "";
            switch (data.fileType) {
                case "sync":
                    ctype = TempoUtils.locale("aidsview.sync_service");
                    $createTaskBtn.hide();
                    break;
                case "async":
                    ctype = TempoUtils.locale("aidsview.async_service");
                    $createTaskBtn.show();
                    status = TempoUtils.locale("aidsview.servicePublished");
                    break;
                case "stream":
                    ctype = TempoUtils.locale("aidsview.stream_service");
                    $createTaskBtn.hide();
                    break;
            }

            $('.tempo-ai-app-rightzone-mid-right-info span[id="ca-type"]').text(ctype);
            $('div[objid="' + data.id + '"] .tempo-ai-app-rightzone-mid-right-info span[id="service_status"]').text(status);
            var flowname = data.description;
            $('.tempo-ai-app-rightzone-top span[id="belong_flow"]').text(flowname).attr('title', flowname);
            var catime = TempoUtils.locale("aidsview.published_in");
            catime += formatCreateTime(data.createTime);
            $('.tempo-ai-app-rightzone-top span[id="ca-time"]').text(catime);
            $rightappView.attr("objid", data.id);
            $rightappView.attr("flowid", data.resourceid);
            isShowShareDirectory = false;
            if (data.modeltype == "PRIV") {
                $shareBtn.show();
                $selectBtn.hide();
                $sharePath.hide();
            } else {
                $shareBtn.hide();
                $selectBtn.show();
                showSharePath(data.id);
            }
        },
        loadRigPage: function (rsManageId, tag) {
            if (!tag) {
                $('.tempo-ai-app-rightzone-mid li.unsort').hide();
            } else {
                $('.tempo-ai-app-rightzone-mid li.unsort').show();
            }
            $('.tempo-ai-app-rightzone-mid').off('click').on('click', "li", function (e) {
                var vurl = $(e.target).data("v");
                $(this).siblings().removeClass("tempo-ai-app-rightzone-mid-select");
                $(this).addClass("tempo-ai-app-rightzone-mid-select");
                if (vurl == null) {
                    return;
                }
                $('.tempo-ai-app-rightzone-bot-service').empty();
                $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&t=" + TempoUtils.uuid(), $('.tempo-ai-app-rightzone-bot-service'));
            })
            $('.tempo-ai-app-rightzone-mid li:eq(0)').trigger('click');
        }
    }

    var flowClickEvent = {
        modifyInfo: function (data) {
            syncParentGrayId = data.parentId;
            //同步服务流程名称
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-flow-name-by-id',
                method: 'POST',
                data: {
                    id: data.id
                },
                success: function (flowData) {
                    $('.tempo-ai-app-rightzone-top span[id="ca-name"]').text(flowData.data.name).attr('title', flowData.data.name);
                    $('.tempo-ai-app-rightzone-top span[id="belong_flow"]').text(flowData.data.name).attr('title', flowData.data.name);
                    //添加同步服务标识
                    var span = $($('.tempo-ai-app-rightzone-top span[id="ca-name"]')[0]);
                    span.next().remove();
                    //挂载的同步服务流程类型
                    if ("plflow" == flowData.data.processType) {
                        var width = span.width();
                        var plImg = $("<img/>").addClass("tempo-sync-service-pl-image");
                        span.after(plImg);
                        plImg.attr("src", contextPath + "/css/images/pl_icon.png");
                        if (width >= 420) {
                            plImg.css("margin-left", "-15px").css("margin-top", "-28px");
                        } else {
                            plImg.css("margin-left", "5px").css("margin-top", "-28px");
                        }
                    }
                }
            });
            //灰度服务中同步服务创建者
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-creator-name-by-userid',
                method: 'POST',
                data: {
                    id: data.creator
                },
                success: function (userData) {
                    $('.tempo-ai-app-rightzone-top span[id="ca-creator"]').text(userData.data.USER_NAME).attr("title", userData.data.USER_NAME);
                }
            });
            $.ajax({
                url: contextPath + '/api/ai/mineresource/getThemeNameByCategoryId',
                method: 'POST',
                data: {
                    id: data.id
                },
                success: function (themeName) {
                    $('.tempo-ai-app-rightzone-top span[id="belong_theme"]').text(themeName).attr('title', themeName);
                }
            });
            var ctype = "";
            var status = "";
            if (data.type == "sync") {
                ctype = TempoUtils.locale("aidsview.sync_service");
                $createTaskBtn.hide();
            }

            $('.tempo-ai-app-rightzone-mid-right-info span[id="ca-type"]').text(ctype);
            $('div[objid="' + data.id + '"] .tempo-ai-app-rightzone-mid-right-info span[id="service_status"]').text(status);
            $('.tempo-ai-app-rightzone-top span[id="ca-time"]').text(TempoUtils.locale("aidsview.published_in") +
                formatCreateTime(data.createTime));
            $rightappView.attr("objid", data.id);
            $rightappView.attr("flowid", data.themeId);
            isShowShareDirectory = false;
            if (data.modeltype == "PRIV") {
                $shareBtn.show();
                $selectBtn.hide();
                $sharePath.hide();
            } else {
                $shareBtn.hide();
                $selectBtn.show();
                showSharePath(data.id);
            }
        },
        loadRigPage: function (rsManageId, tag) {
            if (!tag) {
                $('.tempo-ai-app-rightzone-mid li.unsort').hide();
            } else {
                $('.tempo-ai-app-rightzone-mid li.unsort').show();
            }
            $('.tempo-ai-app-rightzone-mid').off('click').on('click', "li", function (e) {
                var vurl = $(e.target).data("v");
                $(this).siblings().removeClass("tempo-ai-app-rightzone-mid-select");
                $(this).addClass("tempo-ai-app-rightzone-mid-select");
                if (vurl == null) {
                    return;
                }
                $('.tempo-ai-app-rightzone-bot-service').empty();
                $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&t=" + TempoUtils.uuid(), $('.tempo-ai-app-rightzone-bot-service'));
            })
            $('.tempo-ai-app-rightzone-mid li:eq(0)').trigger('click');
        }
    };

    var GrayClickEvent = {
        modifyInfo: function (data, tag) {
            //隐藏案例库更新时间图标
            if($(".tempo-case-tag-create-time").length > 0){
                $(".tempo-case-tag-create-time").css("display","none");
            }
            $('.tempo-ai-app-rightzone-top-gray span[id="ca-grayname"]').text(data.name).attr('title', data.name);
            $('.tempo-ai-app-rightzone-top-gray span[id="belong_flow_gray"]').text(data.name).attr('title', data.name);
            if ($('.tempo-ai-app-rightzone-top-gray span[id="belong_flow_gray"]').text().length > 25) {
                var substring = $('.tempo-ai-app-rightzone-top-gray span[id="belong_flow_gray"]').text().substring(0, 25);
                $('.tempo-ai-app-rightzone-top-gray span[id="belong_flow_gray"]').text(substring + "...");
            }
            //灰度服务中同步服务创建者
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-creator-name-by-id',
                method: 'POST',
                data: {
                    id: data.creatorName
                },
                success: function (userData) {
                    $('.tempo-ai-app-rightzone-top-gray span[id="ca-creator-gray"]').text(userData.data.USER_NAME).attr("title", userData.data.USER_NAME);
                }
            });
            var ctype = "";
            if (data.type == "gray") {
                ctype = TempoUtils.locale("aidsview.gray");
                $createTaskBtn.hide();
            }
            $('.tempo-ai-app-rightzone-mid-right-info-gray span[id="ca-type-gray"]').text(ctype);
            $('.tempo-ai-app-rightzone-top-gray span[id="ca-time-gray"]').text(TempoUtils.locale("aidsview.published_in") +
                formatCreateTime(data.creatTime));
            $rightGrayView.attr("objid", data.id);
            isShowShareDirectory = false;
            //灰度服务是否分享
            $.ajax({
                url: contextPath + '/api/ai/mine/gray/get-share-type',
                method: 'POST',
                data: {
                    id: data.id
                },
                success: function (result) {
                    grayShareFlag = result.success;
                    if (!grayShareFlag) {
                        $shareBtn.show();
                        $selectBtn.hide();
                        $sharePath.hide();
                    } else {
                        $shareBtn.hide();
                        $selectBtn.show();
                    }
                }
            });
        },
        loadRigPage: function (rsManageId, tag) {
            if (!tag) {
                $('.tempo-ai-app-rightzone-mid-gray li.unsort').hide();
            } else {
                $('.tempo-ai-app-rightzone-mid-gray li.unsort').show();
            }
            $('.tempo-ai-app-rightzone-mid-gray').off('click').on('click', "li", function (e) {
                var vurl = $(e.target).data("v");
                $(this).siblings().removeClass("tempo-ai-app-rightzone-mid-select-gray");
                $(this).addClass("tempo-ai-app-rightzone-mid-select-gray");
                if (vurl == null) {
                    return;
                }
                $('.tempo-ai-app-rightzone-bot-gray-service').empty();
                if ("grayconfiguration" == vurl) {
                    $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&flag=" + false + "&&t=" + TempoUtils.uuid(), $('.tempo-ai-app-rightzone-bot-gray-service'));
                } else {
                    $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + rsManageId + "&&t=" + TempoUtils.uuid(), $('.tempo-ai-app-rightzone-bot-gray-service'));
                }
            });
            $('.tempo-ai-app-rightzone-mid-gray li:eq(0)').trigger('click');
        }
    };

    var getContextMenu = function (itemData, level) {
        var menuMapping = {};

        function render(type, level) {
            var menu = getPubMenu(type, level);
            var contextmenu = $("<ul class='tempo-app-tree-menu'/>").appendTo($("body")).contextmenu({
                data: menu,
                select: function (e, ui) {
                    menuHandle.call(this, e, ui);
                }
            });
            menuMapping[type + level] = contextmenu;
        };
        return function (itemData, level) {
            var type = itemData.type;
            if (menuMapping[type + level]) {
                return menuMapping[type + level];
            }
            render(type, level);
            return menuMapping[type + level];
        }
    }();

    var getPubMenu = function (type, level) {
        var menus = getMenus();
        var m;
        if (type == "folder") {
            m = ['createFolder', 'createTheme', 'importTheme', "renameFolder", 'deleteFolder'];
            if (!isCGGLY) {
                m.splice(3, 2);
                m.splice(0, 1);
            } else {
                if (level == 0) {
                    m.splice(3, 2);
                }
                if (level > 1) {
                    m.splice(0, 1);
                }
                if (!isSJRY) {
                    m = m.filter(function (v) {
                        if (v != 'createTheme' && v != 'importTheme') {
                            return true;
                        }
                    })
                }
            }
        } else if (type == "rootnode") {
            m = ['createFolder', 'createTheme', 'importTheme', 'template'];
        } else {
            m = ['edit', 'copy', 'export', 'move', 'delete', 'rename'];
        }
        var showMenus = [];
        for (var i = 0; i < menus.length; i++) {
            if (m.indexOf(menus[i].id) > -1) {
                showMenus.push(menus[i]);
            }
        }
        return showMenus;
    }

    var menuHandle = function (e, ui) {
        var data = ui.linkEl.data;
        var menuId = ui.select.id;
        switch (menuId) {
            case "createFolder" :
                createFolder();// ing
                break;
            case "renameFolder" :
                renameFolder(data, "pub");// ing
                break;
            case "deleteFolder" :
                deleteFolder(data, "pub");// ing
                break;
            case "createTheme" :
                createTheme();// ok!
                break;
            case "importTheme" :
                importTheme(data, "pub");// ok
                break;
            case "copy" :
                copyTheme(data, "pub");// ing OK
                break;
            case "export" :
                exportTheme(data);
                break;
            case "move" :
                moveTheme(data, "pub");// ok 移动到其他文件夹下的校验
                break;
            case "delete" :
                deleteTheme(data.id, "pub");
                break;
            case "edit" :
                editTheme(data);
                break;
            case "rename" :
                renameTheme(data, "pub");// ok
                break;
            case "template" :
                showTemplate(data, "pub");// ok
                initSelectMenu();
                break;
        }
    }

    var showTemplate = function () {
        $('.welcome-page').hide();
        $('.theme-board').hide();
        $rightappView.hide();
        $rightdesignView.hide();
        $('.model-template-page').show();
        var tcontainer = $(".tempo-template-layout");
        var layout = function () {
            tcontainer.layout({
                north: {
                    size: 78,
                    resizable: false,
                    spacing_open: -1,
                    closable: false
                },
            });
        }
        templateCurrentPage = 0;
        templateFlag = "template-config-public";
        /**
         * 初始化tabs 默认先展示公共案例
         */
        $("#tabs_cloud_casebase_config").tabs({
            activate: function (event, ui) {
                //获取tabs的id
                tabsId = ui.newPanel.attr('id');
                templateFlag = tabsId;
                // 为选中的元素添加class
                ui.newTab.addClass('template-config-select-style-udf');
                // 为没有选中的元素去除class
                ui.oldTab.removeClass('template-config-select-style-udf');
                // 如果是公共案例
                if (tabsId === "template-config-public") {
                    //清空筛选条件
                    tagId = "";
                    $("#tag-create-time").next().find("i.el-icon-caret-top").removeClass("icon-change-color");
                    $("#tag-create-time").next().find("i.el-icon-caret-bottom").removeClass("icon-change-color");
                    window.createSelectTag.tag = "";
                    window.searchTemplateName.searchTemplate = '';
                    //去初始化公共库
                    $("#tempo-template-list").empty();
                    templateCurrentPage = 0;
                    listAllTemplates("");
                    listSelfTemplates("","","","","","num");
                }
                // 如果是私人案例
                if (tabsId === "template-config-self") {
                    //清空筛选条件
                    tagId = "";
                    $("#tag-create-time").next().find("i.el-icon-caret-top").removeClass("icon-change-color");
                    $("#tag-create-time").next().find("i.el-icon-caret-bottom").removeClass("icon-change-color");
                    window.createSelectTag.tag = "";
                    window.searchTemplateName.searchTemplate = '';
                    //去初始化私人库
                    $("#tempo-template-list-self").empty();
                    templateCurrentPage = 0;
                    listSelfTemplates("");
                    listAllTemplates("","","","","","num");
                }
            },
        });
        //切换公共案例/私有案例按钮样式更改
        $('#casebase-config-public-li').unbind('click').bind('click', function () {
            changePublicClass();
        });
        $('#casebase-config-self-li').unbind('click').bind('click', function () {
            changeSelfClass();
        });
        //切换到私人案例时 在点击案例库触发下公共案例事件
        $("#tabs_cloud_casebase_config").find('[href$=template-config-public]').trigger('click');
        $('#casebase-config-public-li').addClass('template-config-select-style-udf');
        listAllTemplates("");
        listSelfTemplates("","","","","","num");
        var searchNum = -1;
        //初始化案例名称筛选框
        if(window.searchTemplateName == undefined){
            window.searchTemplateName = new Vue({
                el: '#tempo-search-template',
                data: function () {
                    return {
                        searchTemplate : '',
                    }
                },
                methods: {
                    searchTemplateByName: function (text) {
                        // if(text.indexOf(" ") != -1){
                        //     return;
                        // }
                        var sort = "";
                        var iconTop = $("#tag-create-time").next().find("i.el-icon-caret-top");
                        if(iconTop.hasClass("icon-change-color")){
                            sort = "asc";
                        }else {
                            sort = "desc";
                        }
                        clearInterval(searchNum);
                        searchNum = setTimeout(function () {
                            if(templateFlag == "template-config-public"){
                                listAllTemplates(tagId,$.trim(text),30,0,sort);
                            }else if(templateFlag == "template-config-self"){
                                listSelfTemplates(tagId,$.trim(text),30,0,sort);
                            }
                        },1000);
                    }
                },
            });
            $("#tempo-search-template").parent().find("i.el-input__icon.el-icon-search").unbind('click').bind('click', function (e) {
                window.searchTemplateName.searchTemplateByName(window.searchTemplateName.searchTemplate);
            })
        }else {
            //清空筛选条件
            tagId = "";
            $("#tempo-template-list").empty();
            $("#tag-create-time").next().find("i.el-icon-caret-top").removeClass("icon-change-color");
            $("#tag-create-time").next().find("i.el-icon-caret-bottom").removeClass("icon-change-color");
            window.searchTemplateName.searchTemplate = '';
        }
    }

    //修改设计区公共案例与私有案例样式
    var changePublicClass = function () {
        $('#casebase-config-self-li').css("border-bottom","1px");
        $('#casebase-config-public-li').css("border-bottom","1px solid #333");
    }

    var changeSelfClass = function () {
        $('#casebase-config-public-li').css("border-bottom","1px");
        $('#casebase-config-self-li').css("border-bottom","1px solid #333");
    }

    /**
     * 获取已有的私人案例并进行绘制
     * @param name
     */
    var listSelfTemplates = function (id,name,pageSize,currentPage,sort,num) {
        var progressbar = $("<div/>").tempoprogressbar();
        // 加载列表
        $.ajax({
            url: contextPath + ('/api/ai/resource/template/get-user-template-and-tag'),
            type: 'post',
            data: {
                name: !name ? "" : name,
                id: !id ? "" : id,
                pageSize: !pageSize  ? 30 : pageSize,
                currentPage: !currentPage  ? 0 : currentPage,
                sort: !sort  ? 'desc' : sort
            },
            // async:false,
            dataType: 'json',
            success: function (rs) {
                var userId = rs.data.extraInfo.userId;
                if (rs.success) {
                    // 清空画布
                    if(currentPage == 0){
                        $("#tempo-template-list-self").empty();
                        templateCurrentPage = 0;
                    }
                    var objs = rs.data.data.rows;
                    $("#tempo-template-num-self").text("私有案例 " + (rs.data.data.records > 9999 ? (9999+'...') : + rs.data.data.records) + " ");
                    if(rs.data.data.records == 0 && (id == "" || id == undefined) && (name == "" || name == undefined)){
                        $("#tempo-self-num").css("display","block");
                    }else {
                        $("#tempo-self-num").css("display","none");
                    }
                    if(num == "num"){
                        progressbar.tempoprogressbar("destroy");
                        return;
                    }
                    $("#more-template").remove();
                    for (var i = 0; i < objs.length; i++) {
                        objs[i].nowUserId = userId;
                        var dataTag = {};
                        if(objs[i].tags != null){
                            dataTag = objs[i].tags;
                        }
                        renderNodeSelf(objs[i],dataTag);
                    }
                    //是否加载更多按钮
                    if(rs.data.data.records > $("#tempo-template-list-self").find("div[_widgetname='minetemplatenode']").length){
                        loadMoreTemplate(rs.data.data,"self");
                    }
                    progressbar.tempoprogressbar("destroy");
                }

            },
            error: function () {
                progressbar.tempoprogressbar("destroy");
            }
        });
    }
    /**
     * 渲染图标式节点（私人）
     */
    var renderNodeSelf = function (obj,data) {
        var div = $("<div/>").appendTo($("#tempo-template-list-self"));
        var urlImage = contextPath + "/images/default_workspace.png";
        if (obj == null) {
            return;
        }
        if (obj.thumb) {
            urlImage = "data:image/png;base64," + obj.thumb
        }
        $(div).minetemplatenode({
            data: {
                id: obj.id,
                thumb: urlImage,
                name: obj.name,
                desc: obj.description,
                type: obj.category,
                author: obj.author,
                tag: data,
                args: obj,
                userId: obj.userId,
                isDefault: false,
                isPrivate: true,
                code: obj.code,
                nowUserId: obj.nowUserId,
                editSelfTemplate: function (e) {
                    editTemplate(obj.id,obj.appId);
                },
                deleteSelfTemplate: function (e) {
                    deleteTemplate(obj.code, obj.uptype);
                },
            },
            width: 235,
            height: 316,
            hoverNodeImage: function (e, ui) {
                e.preventDefault();
                e.stopPropagation();
                // 解决前一个悬浮框不消失问题
                $(".node-item-menu-list").hide();
                $(this).find(".node-item-menu-list").show();
                bindNodeMenuEvent(ui, obj);
            },
            mouseleveNodeImage: function (e, ui) {
                if (!e.relatedTarget || ui[0] == e.relatedTarget) {
                    return;
                }
                e.preventDefault();
                e.stopPropagation();
                $(this).find(".node-item-menu-list").hide();
            },
            dblclick: function (e, ui) {
                e.preventDefault();
                e.stopPropagation();
            },
            btnClick: function (e, obj) {
                e.preventDefault();
                e.stopPropagation();
                // changePage(e, this);
            },
            btnDblclick: function (e) {
                e.preventDefault();
                e.stopPropagation();
            },
            textClick: function (e) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    var deleteTemplate = function (code, uptype) {
        //删除案例不需要查询案例是否存在
        removeTemplate(code, uptype);
    }

    var publishFlowIsNull = function (appId) {
        var flag = false;
        $.ajax({
            url: contextPath + '/api/ai/resource/template/flow-publish-info',
            method: 'POST',
            async: false,
            data: {
                appId: appId,
            },
            success: function (rs) {
                if (rs.data) {
                    flag = rs.data;
                }
            }

        })
        return flag;
    }

    var updateTemplate = function (data) {
        $.ajax({
            url: contextPath + '/api/ai/resource/template/is-publish',
            method: 'POST',
            async: false,
            data: {
                appId: data.id,
            },
            success: function (result) {
                var folderId = result.data.id;
                var appId = result.data.appId;
                $.ajax({
                    url: contextPath + '/api/ai/themeTemplateController/temlate/getinfo/' + folderId,
                    method: 'GET',
                    success: function (resultData) {
                        if (resultData.success) {
                            var data = resultData.data[0];
                            data.appId = appId;
                            //编辑案例获取全部标签
                            initGetAllTag();
                            updateTheme("", "编辑", data, folderId);
                        } else {
                            $("<div/>").alert({
                                width: 500,
                                height: 197,
                                msg: resultData.message,
                            });
                        }
                    }
                })
            }
        })
    }

    //发布区更新案例
    var editTemplate = function (id,appId) {
        var folderId = id;
        if (publishFlowIsNull(appId)) {
            $.ajax({
                url: contextPath + '/api/ai/themeTemplateController/temlate/getinfo/' + folderId,
                method: 'GET',
                success: function (resultData) {
                    if(resultData.success){
                        var data = resultData.data[0];
                        data.appId = appId;
                        initGetAllTag();
                        updateTheme("", "编辑", data,folderId);
                    }else {
                        $("<div/>").alert({
                            width: 500,
                            height: 197,
                            msg: resultData.message,
                        });
                    }
                }
            })
        } else {
            $("<div/>").alert({
                width: 500,
                height: 197,
                msg: "案例应用已被取消发布，无法编辑，请重新发布应用！",
            });
        }
    }
    /**
     * 获得所有已有工程并绘制
     */
    var listAllTemplates = function (id,name,pageSize,currentPage,sort,num) {
        var progressbar = $("<div/>").tempoprogressbar();
        // 加载列表
        $.ajax({
            url: contextPath + ('/api/ai/resource/analyse/list-templates'),
            type: 'get',
            data: {
                id:id,
                name: name,
                pageSize: !pageSize ? 30 : pageSize,
                currentPage: !currentPage ? 0 : currentPage,
                sort: !sort ? '' : sort
            },
            // dataType: 'json',
            success: function (rs) {
                if(currentPage == 0){
                    // 清空画布
                    $("#tempo-template-list").empty();
                    templateCurrentPage = 0;
                }
                var objs = rs.data.rows;
                $("#tempo-template-num-public").text("公共案例 " + (rs.data.records > 9999 ? (9999+'...') : + rs.data.records) + " ");
                if(num == "num"){
                    progressbar.tempoprogressbar("destroy");
                    return;
                }
                $("#more-template").remove();
                for (var i = 0; i < objs.length; i++) {
                    var publicFlag = {};
                    if(objs[i].tags != null){
                        publicFlag = objs[i].tags;
                    }
                    renderNode(objs[i],publicFlag);
                }
                if(rs.data.records > $("#tempo-template-list").find("div[_widgetname='minetemplatenode']").length){
                    loadMoreTemplate(rs.data,"public");
                }
                progressbar.tempoprogressbar("destroy");
            },
            error: function () {
                progressbar.tempoprogressbar("destroy");
            }
        });
    }
    /**
     * 渲染图标式节点
     */
    var renderNode = function (obj,publicFlag) {
        var div = $("<div/>").appendTo($("#tempo-template-list"));
        var urlImage = contextPath + "/images/default_workspace.png";
        if (obj.thumb) {
            urlImage = "data:image/png;base64," + obj.thumb
        }
        $(div).minetemplatenode({
            data: {
                id: obj.id,
                tag: publicFlag,
                thumb: urlImage,
                name: obj.name,
                desc: obj.description,
                type: obj.category,
                author: obj.author,
                args: obj,
                isDefault: false,
            },
            width: 235,
            height: 316,
            hoverNodeImage: function (e, ui) {
                e.preventDefault();
                e.stopPropagation();
                // 解决前一个悬浮框不消失问题
                $(".node-item-menu-list").hide();
                $(this).find(".node-item-menu-list").show();
                bindNodeMenuEvent(ui, obj);
            },
            mouseleveNodeImage: function (e, ui) {
                if (!e.relatedTarget || ui[0] == e.relatedTarget) {
                    return;
                }
                e.preventDefault();
                e.stopPropagation();
                $(this).find(".node-item-menu-list").hide();
            },
            dblclick: function (e, ui) {
                e.preventDefault();
                e.stopPropagation();
            },
            btnClick: function (e, obj) {
                e.preventDefault();
                e.stopPropagation();
                // changePage(e, this);
            },
            btnDblclick: function (e) {
                e.preventDefault();
                e.stopPropagation();
            },
            textClick: function (e) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    var loadMoreTemplate = function (objs,type) {
        var flag;
        if(type == "public"){
            flag = $("#tempo-template-list");
        }else if(type == "self"){
            flag = $("#tempo-template-list-self");
        }
        flag.append("<div id=\"more-template\" style='width: calc(100%);height: 42px;float: left;padding: 3px 0px;margin-bottom: 10px'>\n" +
            "                        <hr style=\"border: 1px solid #DCDCDC;width: 10%;float: left;margin-left: calc(40% - 68px);\">\n" +
            "                        <span style=\"color: #999999;cursor: pointer;float: left;text-align: center;width: 108px\">\n" +
            "                        点击加载更多\n" +
            "                        </span>\n" +
            "                        <hr style=\"border: 1px solid #DCDCDC;width: 10%;float: right;margin-right: calc(40% - 44px);\">\n" +
            "                    </div>");
        $("#more-template").unbind('click').bind('click', function (e) {
            templateCurrentPage += 1;
            var text = window.searchTemplateName.searchTemplate;
            var iconTop = $("#tag-create-time").next().find("i.el-icon-caret-top");
            var iconBottom = $("#tag-create-time").next().find("i.el-icon-caret-bottom");
            if(type == "public"){
                if(iconTop.hasClass("icon-change-color")){
                    listAllTemplates(tagId,text,30,templateCurrentPage,"asc");
                }else if(iconBottom.hasClass("icon-change-color")){
                    listAllTemplates(tagId,text,30,templateCurrentPage,"desc");
                }else {
                    listAllTemplates(tagId,text,30,templateCurrentPage,"");
                }
            }
            if(type == "self"){
                if(iconTop.hasClass("icon-change-color")){
                    listSelfTemplates(tagId,text,30,templateCurrentPage,"asc");
                }else if(iconBottom.hasClass("icon-change-color")){
                    listSelfTemplates(tagId,text,30,templateCurrentPage,"desc");
                }else {
                    listSelfTemplates(tagId,text,30,templateCurrentPage,"");
                }
            }
        });
    }

    var bindNodeMenuEvent = function (ui, obj) {
        // 从模板创建
        ui.find('.node-item-menu-createtheme').unbind('click').bind('click', function () {
            var id = obj.id;
            var name = obj.name;
            $.ajax({
                url: contextPath + '/api/ai/themeTemplateController/temlate/get/' + id,
                method: 'GET',
                success: function (resultData) {
                    if(resultData.success){
                        createThemeFromTemplate(id, name);
                    }else {
                        $("<div/>").alert({
                            width: 500,
                            height: 197,
                            msg: resultData.message,
                        });
                    }
                }
            });
        });
        // 查看案例说明
        ui.find('.node-item-menu-detailinfo').unbind('click').bind('click', function () {
            var id = obj.id;
            $.ajax({
                url: contextPath + '/api/ai/themeTemplateController/temlate/get/' + id,
                method: 'GET',
                success: function (resultData) {
                    if(resultData.success){
                        openTemplateInfoDialog(id,obj.name);
                    }else {
                        $("<div/>").alert({
                            width: 500,
                            height: 197,
                            msg: resultData.message,
                        });
                    }
                }
            });
        });
    }
    // 查看案例说明
    var openTemplateInfoDialog = function (id,name) {
        window.open(contextPath + "/api/ai/themeTemplateController/template/preview/" + id + "/" + name, '_blank');
    }

    var hideTemplate = function () {
        $('.tempo-template-search').find("input").val("");
        $('.model-template-page').hide();
    }

    var showWelcome = function (type) {
        hideTemplate();
        $rightTaskView.hide();
        $('.theme-board').hide();
        $rightappView.hide();
        $rightGrayView.hide();
        $rightdesignView.hide();
        if (type == "design") {
            $('.welcome-page-2').hide();
            $('.welcome-page').show();
        } else {
            $('.welcome-page').hide();
            $('.welcome-page-2').show();
            $('.welcome-page-2').find("#tempo-banner-tooltip").css("left","calc(50% - 145px)")
        }
    }

    var hideWelcome = function () {
        $('.welcome-page').hide();
        $('.welcome-page-2').hide();
        $('.theme-board').show();
    }

    // 主题相关操作
    var openTheme = function (data, tag) {
        // 个人空间隐藏发布按钮
        var workSpaceType = $themeContainer.attr("workspacetype");
        if (workSpaceType == "self") {
            $('.publish-btn').hide();
            $('.share-btn').text("分享给");
        } else {
            $('.publish-btn').show();
        }
        if (data.type != 'mining') return;
        var id = data.id;
        // if(window.analyseId == id) return;
        $('body').off('click.modeling');

        if ($('.theme-board').css("display") == "none") {
            hideWelcome();
            hideTemplate();
        }

        // 发布区隐藏
        $rightTaskView.hide();
        $rightappView.hide();
        $(".tempo-strap-header-right").show();

        Eventbus.trigger('preview.theme');
        var analyseStatus = TempoMineUtils.analyseStatus;
        analyseStatus.empty();

        //加载已发布的资源列表
        renderPublishScence(data.id);

        $(".theme-blackboard").empty();
        var board = $("<div class='blackboard'></div>").appendTo($(".theme-blackboard"))

        var url = contextPath + '/api/ai/resource/analyse/view/preview?id=' + id;
        $m.loadPage(url, board);
        theme.id = id;
        theme.name = data.name;

        $('#tempo-header-themName').text(data.name).attr('title', data.name);

        //授权信息
        permissionUser();
        $.ajax({
            url: contextPath + '/api/ai/resource/analyse/info',
            method: 'POST',
            data: {
                id: theme.id,
            },
            success: function (data) {
                var dataInfo = data.data;
                $('#theme-creator').text(dataInfo.userName).attr("title", dataInfo.userName);
                $('#app-num').text(dataInfo.appNum);
                $('#flow-num').text(dataInfo.flowNum);
                //创建日期
                $("#theme-time").text(formatCreateTime(dataInfo.createTime, dataInfo.timeDiff));
            }
        })
        $(".theme-more-info").off('click').on('click', function () {
            themeDetail(analyseId);
        });

        if (workSpaceType == "self") {
            $(".tempo-theme-publish-num-div").hide();
        } else {
            $(".tempo-theme-publish-num-div").show();
        }
    }
    window.reloadTheme = function () {
        $refreshBtn.click();
    }

    // 授权人数
    var permissionUser = function () {
        var id = $themeTree.gtree("getSelected").id;
        var workSpaceType = $themeContainer.attr("workspacetype");
        var workSpaceId = $themeContainer.attr("workspaceid");
        var data = {
            resourceId: id,
            workSpaceId: workSpaceId
        };
        if (workSpaceType == "self") {
            data = {resourceId: id};
        }
        $.ajax({
            url: contextPath + "/api/ai/resource/permission/list-users",
            data: data,
            async: false,
            type: 'post',
            success: function (result) {
                $("#theme-share-num").text(result.data.length);
            }
        });

    };

    //格式化日期
    var formatCreateTime = function (createTime, timeDiff) {
        var createTime1 = "";
        if (timeDiff != null) {
            var day = timeDiff.day;
            var hour = timeDiff.hour;
            var min = timeDiff.min;
            createTime1 = DateUtils.formatDate(createTime, 'yyyy-MM-dd');
            if (day > 0 && day < 3) {
                createTime1 = day + "天前";
            }
            if (day == 0 && hour != 0) {
                createTime1 = hour + "小时前";
            }
            if (day == 0 && hour == 0 && min != 0) {
                createTime1 = min + "分钟前";
            }
            if (day == 0 && hour == 0 && min == 0) {
                createTime1 = 1 + "分钟前";
            }
        } else {
//			 var time=DateUtils.getCountTime(DateUtils.formatDate(createTime, 'yyyy-MM-dd')).split(" ");
            createTime1 = DateUtils.formatDate(createTime, 'yyyy-MM-dd');
//			 if(time[0]<=3&&time[0]>0){
//				 createTime1=time[0]+"天前";
//			 }
//			 if(time[0]==0&&time[1]!=0){
//				 createTime1=time[1]+"小时前";
//			  }
//			 if(time[0]==0&&time[1]==0){
//				 createTime1=time[2]+"分钟前";
//			 }
//			 if(time[0]==0&&time[1]==0&&time[2]==0){
//				 createTime1=1+"分钟前";
//			 }
        }

        return createTime1;
    }
    var initPublish = function () {
        var workSpaceType = $themeContainer.attr("workspacetype");
        if (workSpaceType == "self") {
            $("#tempo-theme-publish").hide();
        }
        $(".tempo-theme-publish-num-div").mouseover(function () {
            $("#tempo-publish-list").css("left", ($(this).offset().left - 227) + "px").show();
        });
        $("#tempo-publish-list").mouseover(function () {
            $("#tempo-publish-list").show();
        });
        $(".tempo-theme-publish-num-div,#tempo-publish-list").mouseout(function () {
            $("#tempo-publish-list").hide();
        });

    };

    //已发布的资源列表
    var renderPublishScence = function (id) {
        $(".tempo-theme-publish-num-div").off();
        $("#tempo-publish-list ul").empty();
        $.ajax({
            url: contextPath + "/api/ai/resource/list-published",
            data: {themeId: id},
            type: 'post',
            success: function (resultData) {
                if (resultData.success) {
                    var data = resultData.data;
                    var $publishList = $("#tempo-publish-list").find("ul");
                    if (data.length == 0) {
                        var li = $("<li/>").appendTo($publishList);
                        $("<span/>", {
                            text: "已发布资源可以在此跳转",
                        }).appendTo(li);
                    }
                    for (var i = 0; i < data.length; i++) {
                        var li = $("<li/>", {
                            id: data[i].id,
                            name: data[i].name,
                            class: "tempo-punlish-link"
                        }).appendTo($publishList);
                        $("<span/>", {
                            class: "tempo-scene-icon tempo-ai-api-icon-tree-16 tempo-ai-api-icon-tree-16-position-8",
                        }).appendTo(li);
                        $("<span/>", {
                            class: "tempo-punlish-item ",
                            title: data[i].name,
                            text: _subString(data[i].name, 10)
                        }).appendTo(li);
                        $("<span/>", {
                            class: "ui-icon tempo-ui-icon tempo-ui-icon-uparrows-undertint tempo-punlish-link-icon",
                        }).appendTo(li);
                    }
                    $(".tempo-punlish-link").click(function () {
                        var id = $(this).attr("id");
                        var name = $(this).attr("name");
                        tabsClick({
                            id: id,
                            name: name
                        });
                    });

                    initPublish();

                } else {

                }
            }
        });
    };


    var tabsClick = function (data) {
        linkPublishId = data.id;
        searchWord = data.name;
        $pubSearchBar.searchbar("setValue", searchWord);
        $themeTabs.children("li:last-child").trigger("click", data.id);
    }

    var editTheme = function (data) {
        var id = data.id;
        var url = contextPath + '/api/ai/resource/analyse/view/index?id=' + id;
        var span = $('.model-selected > span.tempo-mine-tab-curSelect')
        var linkId = span.attr('linkId');
        // 当当前打开的主题是要编辑的主题，则打开当前选中的分析页签
        if (linkId && theme.id == id) {
            url += '#' + linkId;
        }
        initTopDialog(name, url)
        // window.open(url, '_blank');
    };


    var initTopDialog = function (name, url) {
// 		if(window.parent.topDialog) {
// 			// title, url, beforeCloseFn, closedFn,refreshFn
// 			window.parent.topDialog(name, url, function(frame) {
// 				if(frame.$('#tempo-mine-model-tabs .tempo-mine-tab-change').length) {
// 					return TempoUtils.locale("mine.unSavePromot");
// 				} else {
// 					return null;
// 				}
// 			}, function(iframe,treeSlectId) {
// 			},function(frame,iframe,themeId,dialog){
// 				var window=iframe[0].contentWindow;
// 				var src=contextPath+"/api/ai/resource/analyse/view/index?id=" + analyseId;;
// 				var span = window.$('.model-selected > span.tempo-mine-tab-curSelect')
// 				var linkId = span.attr('linkId');
// 				src += '#' + linkId;
// //				var data=window.$(".tempo-story-tabs").find(".tempo-story-tab-curSelect").data();
// 				dialog.find('iframe').attr('src', src);
// 				dialog.dialog("destroy").remove();
// 				initTopDialog(name,src)
// 			});
// 		} else {
        window.open(url, '_blank');
        //}
    }

    var openShareView = function (data) {
        var buttons = [{
            text: TempoUtils.locale("bidesign.workspace_comfirm"),
            click: function () {
                editPriSave(dialog, data.subjectId);
                dialog.dialog("close");
            }
        }, {
            text: TempoUtils.locale("bidesign.workspace_cancel"),
            click: function () {
                dialog.dialog("close");
            }
        }];
        if ($themeContainer.attr("workspacetype") == 'self') {
            buttons = [{
                text: TempoUtils.locale("bidesign.workspace_comfirm"),
                click: function () {
                    dialog.dialog("close");
                }
            }];
        }
        var dialog = $('<div>').appendTo($('body'));
        dialog.dialog({
            title: TempoUtils.locale("bidesign.has_shared"),
            width: 750,
            height: 500,
            modal: true,
            resizable: false,
            open: function () {
                var url = contextPath + '/api/ai/resource/permission/view/index';
                $m.loadHtml(url, dialog, 'theme-priv', data)
            },
            close: function () {
                dialog.dialog("destroy").remove();
            }, buttons: buttons
        })
    }
    /**
     * 编辑时获取权限配置数据
     */
    var editPriSave = function (dialog, resouceId) {
        var grid = dialog.find("#tempo-resouce-permission-grid");
        var data = grid.datagrid('getRowData');
        var newPrivi = [], deletePrivi = [];
        if (data && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                var $switchbutton = $('div[id=' + data[i].HASPRIVI.substr(data[i].HASPRIVI.indexOf("id=") + 4, 32) + ']');
                // 如果value=manager ,管理权限 跳过
                if ($switchbutton.attr('value') == 'manager') {
                    continue;
                }
                // 如果value=1,有权限，如果选择了关闭，去除权限
                if ($switchbutton.attr('value') == '1' && !$switchbutton.switchbutton('option').open) {
                    deletePrivi.push(data[i].CODE);
                }
                // 如果value=0,无权限，如果选中了开启，新增
                if ($switchbutton.attr('value') == '0' && $switchbutton.switchbutton('option').open) {
                    newPrivi.push(data[i].CODE);
                }
            }
        }
        if (deletePrivi.length > 0) {
            $.ajax({
                url: contextPath + "/api/ai/resource/permission/revoke-by-user-resource",
                data: {
                    users: deletePrivi.join(','),
                    resourceId: resouceId
                },
                async: false,
                type: 'post',
                success: function (result) {
                }
            });
        }
        if (newPrivi.length > 0) {
            $.ajax({
                url: contextPath + "/api/ai/resource/permission/grant",
                method: 'POST',
                async: false,
                data: {
                    resourceId: resouceId,
                    users: newPrivi.join(',')
                },
                success: function (data) {
                }
            });
        }
    }
    var openPublishView = function (data) {
        var id = data.id;
        var dialog = $("<div/>", {
            'class': 'tempo-theme-publish-dialog'
        });
        var url = contextPath + '/api/ai/app/view/publish?subjectId=' + data.id;
        $m.loadPage(url, dialog);
        dialog.dialog({
            title: TempoUtils.locale("aidsview.theme_publish"),
            width: 900,
            height: 510,
            modal: true,
            resizable: false,
            close: function () {
                dialog.dialog("destroy").remove();
                // 更新页签流程信息
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/info',
                    method: 'POST',
                    data: {
                        id: analyseId,
                    },
                    success: function (data) {
                        var dataInfo = data.data;
                        $('#flow-num').text(dataInfo.flowNum);
                    }
                })
            }
        })
    }

    var openThemePreview = function () {
        $('.blackboard-other').hide();
        $('.blackboard').show();
    }

    var copyTheme = function (data, tag) {
        var progressbar = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/resource/analyse/copy';
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                id: data.id,
            },
            success: function (rs) {
                if (rs && rs.success) {
                    failTip(TempoUtils.locale("aidsview.theme_copy_tip"));
                    rs.data.fileType = 'FILE';
                    rs.data.belong = '1';
                    var pid = rs.data.folderId;
                    if (pid == null || pid == "-1") {
                        $themeTree.gtree('reload');
                    } else {
                        $themeTree.gtree('reloadItem', pid);
                    }
                } else {
                    failTip(rs.message);
                }
                progressbar.tempoprogressbar("destroy");
            }
        })

    }

    var addThemeToobarSelectClass = function (ele) {
        ele.removeClass("ui-button");
        ele.removeClass("tempo-button");
        ele.addClass("theme-strap-header-toolbar-select");
    }

    var exportTheme = function (data, ele) {
        var id = data.id;
        TempoUtils.download({
            url: contextPath + '/api/ai/resource/analyse/export',
            data: {
                id: id
            },
            method: 'get'
        })
        // var url = contextPath + '/api/ai/resource/analyse/export?id=' + id;
        // window.open(url);
    }

    var moveTheme = function (data, tag) {
        curFolderId = "";
        var id = data.id;
        var folderid = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-move'
        });
        dialog.append("<div id='folderTreeDiv'><div id='folderTree'></div></div>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 400,
            resizable: false,
            title: TempoUtils.locale("aidsview.theme_move"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    folderid = curFolderId;
                    var url = contextPath + '/api/ai/resource/analyse/move';
                    if (folderid != "") {
                        var progressbar = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: url,
                            method: 'POST',
                            data: {
                                id: id,
                                folderId: folderid,
                                workSpaceId: $('.theme-container').attr("workspaceid")

                            },
                            success: function (rs) {
                                if (rs && rs.success) {
                                    dialog.dialog("destroy").remove();
                                    $themeTree.gtree('reload');
                                } else {
                                    failTip(rs.message);
                                }
                                progressbar.tempoprogressbar("destroy");
                            }
                        })
                    } else {
                        failTip(TempoUtils.locale("aidsview.theme_move_tip"));
                    }
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        openTree(dialog, tag);
    }

    var copyThemeTo = function (data, tag) {
        curFolderId = "";
        curworkSpaceId = workSpaceId;
        var id = data.id;
        var folderid = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-move'
        });
        var dialogel = "<div class='tempo-strap-dialog-tree-container' >" +
            "<select id='workSpaceList' style='left:65%;' ></select>" +
            "<div id='folderTree' style='height:80%;margin-top:15px;'class='tempo-strap-dialog-tree'></div>" +
            "</div>";
        dialog.append(dialogel);
        dialog.dialog({
            modal: true,
            width: 500,
            height: 400,
            resizable: false,
            title: TempoUtils.locale("aidsview.COPY"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var url = contextPath + '/api/ai/resource/analyse/copy';
                    folderid = curFolderId;
                    if (folderid != "") {
                        var progressbar = $("<div/>").tempoprogressbar();
                        $.ajax({
                            url: url,
                            method: 'POST',
                            data: {
                                id: id,
                                folderId: folderid,
                                workSpaceId: curworkSpaceId
                            },
                            success: function (rs) {
                                if (rs && rs.success) {
                                    rs.data.fileType = 'FILE';
                                    rs.data.belong = "1";
                                    rs.data.parentId = rs.data.folderId;
                                    var pid = rs.data.parentId;
                                    if (pid == "-1" || pid == null) {
                                        $themeTree.gtree('reload');
                                    } else {
                                        $themeTree.gtree('reloadItem', pid);
                                    }
                                    dialog.dialog("destroy").remove();
                                } else {
                                    failTip(rs.message);
                                }
                                progressbar.tempoprogressbar("destroy");
                            }
                        })
                    } else {
                        failTip(TempoUtils.locale("aidsview.theme_move_tip"));
                    }
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        openTree(dialog, tag);
        createWorkSpaceList(dialog);
    }

    var createWorkSpaceList = function (dialog) {
        var data = getWorkSpaceList();
        var $selectmenu = dialog.find("#workSpaceList");
        for (var i = 0; i < data.length; i++) {
            $("<option>", {
                "value": data[i].id,
                "text": data[i].text
            }).appendTo($selectmenu);
        }
        $selectmenu.selectmenu({
            change: function (e, element) {
                curworkSpaceId = element.item.value;
                var process = $("<div/>").tempoprogressbar();
                $.ajax({
                    url: contextPath + '/api/ai/resource/tree/list-own-folder',
                    method: 'POST',
                    data: {
                        sort: 'ASC',
                        workSpaceId: curworkSpaceId
                    },
                    success: function (data) {
                        var treeData = dataProcess(data.data[0]);
                        treeData = [treeData];
                        var $folderTree = $("#folderTree");
                        $folderTree.gtree({
                            data: treeData
                        });
                        $folderTree.gtree("reload");
                    }
                }).done(function () {
                    process.tempoprogressbar("destroy");
                });
            }
        });
        $selectmenu.val(workSpaceId).selectmenu('refresh');
        $('#workSpaceList-menu li').width(150);
    }

    var dataProcess = function (data) {
        if ($.isArray(data)) {
            for (var i in data) {
                dataProcess(data[i]);
            }
        } else {
            data.title = data.name;
            data.icon = 'ui-icon tempo-ui-icon tempo-ui-icon-no-mutual ';
            if (data.fileType == 'FILE') {
                data.icon += 'tempo-ui-icon-scene';
            } else if (data.fileType == 'FOLDER') {
                data.icon += 'tempo-ui-icon-api-folder-close';
                data.groupType = 'folder';
                data.type = 'group';
            } else {
                data.groupType = 'folder';
                data.type = 'group';
                data.icon += 'tempo-ui-icon-api-folder-close';
            }
            if (data.children && data.children.length) {
                dataProcess(data.children);
            }
        }
        return data;
    }

    var deleteTheme = function (id, tag) {
        $("<div>").confirm({
            width: 500,
            height: 197,
            msg: TempoUtils.locale("aidsview.delete_tip"),
            ok: function () {
                var progressbar = $("<div/>").tempoprogressbar();
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/delete',
                    method: 'POST',
                    data: {
                        id: id,
                    },
                    success: function (rs) {
                        if (rs && rs.success) {
                            failTip(TempoUtils.locale("aidsview.theme_delete_tip"));
                            $themeTree.gtree('removeItem', id);
                            showWelcome("design");
                        } else {
                            failTip(rs.message);
                        }
                        progressbar.tempoprogressbar("destroy");
                    }
                })
            }
        });
    }
    var removePrivilege = function (data) {
        var userid = currentUserId;
        var id = data.id;
        var parentId = data.parentId
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate'
        });
        dialog.append("<div style='text-align:center;width:100%;height:100%;margin-top: 14px;'><span style='font-size:14px;margin-left:10px'>" + TempoUtils.locale("aidsview.remove_tip") + "</span></>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 197,
            resizable: false,
            title: TempoUtils.locale("mine.prompt"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    dialog.dialog("destroy").remove();
                    var progressbar = $("<div/>").tempoprogressbar();

                    $.ajax({
                        url: contextPath + '/api/ai/mine/publish/existService',
                        method: 'POST',
                        data: {
                            themeId: id
                        },
                        success: function (data) {
                            // 无已上架流程
                            if (!data) {
                                $.ajax({
                                    url: contextPath + '/api/ai/resource/permission/revoke-by-all',
                                    method: 'POST',
                                    data: {
                                        resId: id,
                                        users: userid,
                                    },
                                    success: function (data) {
                                        var item = $themeTree.gtree("getItem", id);
                                        var parentitem = item.parent().prev("div")[0];
                                        var parentid = $(parentitem).attr("_itemid")
                                        var parentData = {id: parentid};
                                        $themeTree.gtree("removeItem", id);
                                        // 为空时，移除文件夹
                                        var childrenLength = $themeTree.gtree("getChildren", parentData).length;
                                        if (childrenLength == 0) {
                                            $themeTree.gtree("removeItem", parentid);
                                        }
                                        showWelcome("design");
                                        progressbar.tempoprogressbar("destroy");
                                    }
                                })
                            } else {
                                progressbar.tempoprogressbar("destroy");
                                failTip(TempoUtils.locale("aidsview.removetip"));
                            }
                        }
                    })
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
    }
    var renameTheme = function (data, tag) {
        var id = data.id;
        var newName = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate'
        });
        dialog.append("<div style='text-align:center;width:100%;height:100%;'><form><table><tr><td><span class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</span></td><td><input type='text' id='renameTheme'></td></tr><tr><td><span class='theme_operate_input_name'>" + TempoUtils.locale("aidsview.description") + "</span></td><td style='padding: 3px;'><textarea  placeholder='" + TempoUtils.locale("aidsview.max_200_char") + "' style='height:80px;resize:none;width: 263px' id='themeDescription'></textarea></td></tr></table></form></div>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 260,
            resizable: false,
            title: TempoUtils.locale("aidsview.RENAME"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var form = dialog.find("form");
                    if (!form.formValidate()) {
                        return;
                    }
                    var url = contextPath + '/api/ai/resource/analyse/rename';
                    newName = dialog.find("#renameTheme").val();
                    desc = dialog.find("#themeDescription").val();
                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: {
                            id: id,
                            name: newName,
                            workSpaceId: $('.theme-container').attr("workspaceid"),
                            description: desc
                        },
                        success: function (rs) {
                            if (rs && rs.success) {
                                //获取当前选中的树节点数据
                                var treeData = $themeTree.gtree("getSelected");
                                //判断当前选中的树节点是否是重命名的节点
                                if (treeData && treeData.id == id) {
                                    $("#tempo-header-themName").text(newName).attr('title', data.name);
                                    $themeName.text(newName).attr('title', newName);
                                }
                                data.name = newName;
                                theme.name = newName;
                                data.description = desc;
                                $themeTree.gtree("updateItemName", id, newName);
                                dialog.dialog("destroy").remove();
                            } else {
                                failTip(rs.message);
                            }
                        }
                    })
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        $("#renameTheme").val(data.name);
        $("#themeDescription").val(data.description);
        nameValid(dialog.find("#renameTheme"));
        descValid(dialog.find("#themeDescription"));
    }

    var renameFolder = function (data, tag) {
        var id = data.id;
        var newName = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate'
        });
        dialog.append("<div style='width:100%;height:100%;'><form class='formLayout' style='margin-top:10px'><span class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</span><input type='text' id='renameFolder'></form></>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 197,
            resizable: false,
            title: TempoUtils.locale("aidsview.RENAME"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var form = dialog.find("form");
                    if (!form.formValidate()) {
                        return;
                    }
                    newName = dialog.find("input").val();
                    var url = contextPath + '/api/ai/resource/folder/rename';
                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: {
                            id: id,
                            name: newName,
                            workSpaceId: $('.theme-container').attr("workspaceid")
                        },
                        success: function (rs) {
                            if (rs && rs.success) {
                                $themeTree.gtree("updateItemName", id, newName);
                                if ($pubThemeTree.hasClass("tempo-gtree")) {
                                    var item = $pubThemeTree.gtree("getItem", id);
                                    if (item && item.length > 0) {
                                        $pubThemeTree.gtree("updateItemName", id, newName);
                                    }
                                }
                                dialog.dialog("destroy").remove();
                            } else {
                                failTip(rs.message);
                            }
                        }
                    })
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        $("#renameFolder").val(data.name);
        nameValid(dialog.find("#renameFolder"));
    }

    var themeDetail = function (id) {
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate'
        });
        dialog.append("<div style='text-align:center;width:100%;height:100%;'><div class='detailInfo'><div class='detailInfo-basicInfo'><div class='rs-right-top-l tempo-api-icon-48 tempo-api-icon-48-position-4 '></div></div></div>");
        var tab = $('<div class="ai-theme-detailinfo-tab"><div class="shareInfo"><span>' + TempoUtils.locale("aidsview.theme_share_info") + '</span></div><div class="historyInfo"><span>' + TempoUtils.locale("aidsview.theme_history_info") + '</span></div></div>').appendTo(dialog.find(".detailInfo"));
        var content = $('<div class="infoContent" id="ai-theme-mine-infoContent"></div>').appendTo(dialog.find(".detailInfo"));
        $("<table id='ai-mine-sharedinfo-grid'></table>").appendTo(content);
        dialog.dialog({
            modal: true,
            width: 680,
            height: 480,
            resizable: false,
            title: TempoUtils.locale("aidsview.theme_detail"),
            buttons: [{
                text: TempoUtils.locale("mine.guanbi"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                dialog.dialog("destroy").remove();
            },
            open: function () {
                // 初始化基本信息
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/info',
                    method: 'POST',
                    data: {
                        id: id,
                    },
                    success: function (data) {
                        var dataInfo = data.data;
                        dialog.find('.basicinfo').remove();
                        if (dataInfo.themeDesc == null || dataInfo.themeDesc == "") {
                            dataInfo.themeDesc = TempoUtils.locale("mine.black")
                        }
                        var $themeDesc = $('<div class="basicinfo"><div class="theme-light-color" id="theme-creator" title="' + TempoUtils.locale("aidsview.create_user") + dataInfo.userName + '"><span class="theme-creator-info">' + TempoUtils.locale("aidsview.create_user") + dataInfo.userName + '</span><span style="margin: 0px 10px;color:#d7dde5">|</span><span class="theme-light-color">' + TempoUtils.locale("aidsview.theme_time") + '</span><span class="theme-deep-color" id="create-time">' + DateUtils.formatDateTime(dataInfo.createTime == null ? dataInfo.createtime : dataInfo.createTime) + '</span></div>' +
                            '<div class="theme-info-div" id="theme-desc" title="' + dataInfo.themeDesc + '"></div>' +
                            '<div class="theme-info-div"><span class="theme-basic-item">' + TempoUtils.locale("aidsview.flow_num") + '</span><span class="theme-deep-color" id="flow-num">' + dataInfo.flowNum + "</span>" +
                            '<span style="margin: 0px 10px;color:#d7dde5">|</span><span class="theme-light-color">' + TempoUtils.locale("aidsview.publish_num") + '</span><span class="theme-deep-color" id="publsh-num">' + dataInfo.appNum + '</span>' +
                            '</div>' +
                            '<div class="theme-info-div" style="padding-left:88px"><span class="theme-basic-item">' + TempoUtils.locale("aidsview.server-sync-num") + '</span><span class="theme-deep-color" id="server-sync-num">' + dataInfo.serverSyncCount + "</span>" +
                            '<span style="margin: 0px 10px;color:#d7dde5">|</span><span class="theme-light-color">' + TempoUtils.locale("aidsview.server-asyn-num") + '</span><span class="theme-deep-color" id="server-asyn-num">' + dataInfo.serverAsyncCount + '</span>' +
                            '<span style="margin: 0px 10px;color:#d7dde5">|</span><span class="theme-light-color">' + TempoUtils.locale("aidsview.server-stream-num") + '</span><span class="theme-deep-color" id="server-stream-num">' + dataInfo.serverStreamCount + '</span>' +
                            '</div></div>').appendTo($('.detailInfo-basicInfo'));
                        $themeDesc.find("#theme-desc").text(TempoUtils.locale("aidsview.description2") + dataInfo.themeDesc);
                    }
                });

                // 初始化-分享信息、历史信息
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/list-shared-info',
                    method: 'POST',
                    data: {
                        id: id,
                    },
                    success: function (data) {
                        initShareGrid(data.data);
                        $(".shareInfo").addClass("ai-theme-info-selecttab").removeClass("ai-theme-info-unselecttab");
                        $(".historyInfo").addClass("ai-theme-info-unselecttab").removeClass("ai-theme-info-selecttab");

                        // 页签事件
                        $(".shareInfo").off('click').on('click', function (e) {
                            $("#gbox_ai-mine-historyinfo-grid").hide();
                            $("#gbox_ai-mine-sharedinfo-grid").show();
                            if (!$(this).hasClass('ai-theme-info-selecttab')) {
                                $(this).addClass("ai-theme-info-selecttab").removeClass("ai-theme-info-unselecttab");
                                $(".historyInfo").addClass("ai-theme-info-unselecttab").removeClass("ai-theme-info-selecttab");
                            }
                        });


                        $(".historyInfo").off('click').on('click', function (e) {
                            $("#gbox_ai-mine-sharedinfo-grid").hide();
                            $(this).addClass("ai-theme-info-selecttab").removeClass("ai-theme-info-unselecttab");
                            $(".shareInfo").addClass("ai-theme-info-unselecttab").removeClass("ai-theme-info-selecttab");

                            if ($("#gbox_ai-mine-historyinfo-grid").length > 0) {
                                $("#gbox_ai-mine-historyinfo-grid").show();
                            } else {
                                $.ajax({
                                    url: contextPath + '/api/ai/resource/analyse/history',
                                    method: 'POST',
                                    data: {
                                        id: id,
                                    },
                                    success: function (data) {
                                        $("<table id='ai-mine-historyinfo-grid'></table>").appendTo(content);
                                        initHistoryGrid(data.data);
                                    }
                                })
                            }
                        });
                    }
                });

            }
        });
    }

    var initShareGrid = function (data) {
        var colsModel = [{
            name: 'index',
            index: 'index',
            hidden: true
        }, {
            name: 'username',
            index: 'username',
            align: 'center',
            width: '80px',
            sortable: false
        }, {
            name: 'name',
            index: 'name',
            align: 'center',
            width: '80px',
            sortable: false
        }, {
            name: 'dept',
            index: 'dept',
            align: 'center',
            width: '80px',
            sortable: false
        }, {
            name: 'role',
            index: 'role',
            align: 'center',
            width: '200px',
            sortable: false
        }];

        var shareInfoGrid = $('#ai-mine-sharedinfo-grid').datagrid({
            datatype: "local",
            data: data,
            height: 120,
            width: 620,
            rownumbers: false,
            hidegrid: false,
            resizable: false,
            striped: true,
            viewrecords: true,
            loadui: 'disable',
            multiselect: false,
            pagination: false,
            colNames: ['index',
                TempoUtils.locale("aidsview.info_name"),
                TempoUtils.locale("aidsview.info_pname"),
                TempoUtils.locale("aidsview.info_dept"),
                TempoUtils.locale("aidsview.info_role")],
            colModel: colsModel
        });
    }

    var initHistoryGrid = function (data) {
        var colsModel = [{
            name: 'operation',
            index: 'operation',
            align: 'center',
            width: '80px',
            sortable: false,
            formatter: function (cellvalue) {
                return TempoUtils.locale("aidsview." + cellvalue);
            }
        }, {
            name: 'operatorcode',
            index: 'operatorcode',
            align: 'center',
            width: '80px',
            sortable: false
        }, {
            name: 'operator',
            index: 'operator',
            align: 'center',
            width: '80px',
            sortable: false
        }, {
            name: 'deptname',
            index: 'deptname',
            align: 'center',
            resizable: false,
            sortable: false
        }, {
            name: 'operatetime',
            index: 'operatetime',
            align: 'center',
            width: '180px',
            sortable: false,
            formatter: function (cellvalue) {
                return DateUtils.formatDateTime(new Date(cellvalue), 'yyyy-MM-dd HH:mm:ss');
            }
        }];

        var historyInfoGrid = $('#ai-mine-historyinfo-grid').datagrid({
            datatype: "local",
            data: data,
            height: 120,
            width: 620,
            rownumbers: false,
            hidegrid: false,
            resizable: false,
            striped: true,
            viewrecords: true,
            loadui: 'disable',
            multiselect: false,
            pagination: false,
            colNames: [TempoUtils.locale("aidsview.info_opt"),
                TempoUtils.locale("aidsview.info_name"),
                TempoUtils.locale("aidsview.info_pname"),
                TempoUtils.locale("aidsview.info_dept1"),
                TempoUtils.locale("aidsview.info_time")],
            colModel: colsModel
        });
    }

    var failTip = function (msg) {
        $("<div/>").alert({
            msg: msg,
        });
    }
    /**
     *删除案例
     */
    var removeTemplate = function (code, uptype) {
        var Dialog = $('<div style="width:100%;height:100%;background-color: #ffffff"/></div>').appendTo($('body'));
        Dialog.dialog({
            modal: true,
            width: 420,
            height: 118,
            title: TempoUtils.locale("mine.prompt"),
            resizable: false,
            closeOnEscape: true,
            close: function () {
                Dialog.remove();
            },
            open: function () {
                $('<div  class="tempo-sys-delete-dialog-content">' + TempoUtils.locale("mine.shanchubukehufu") + '</div>').appendTo($(Dialog));
            },
            buttons: [{
                text: TempoUtils.locale("mine.publish-dialog-sure"),
                id: 'tempo-sys-ok-btn',
                click: function () {
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + "/api/ai/sysconfig/casebase/delete-self-template",
                        data: {
                            //此处和后端路径保持一致
                            filePath: "publish" === uptype ? "theme_templates_self/" + code : "theme_templates/" + code,
                            code: code,
                        },
                        type: 'post',
                        success: function (result) {
                            process.tempoprogressbar('destroy');
                            Dialog.dialog("close");
                            if (result) {
                                $("#tempo-template-list-self").empty();
                                templateCurrentPage = 0;
                                listSelfTemplates();
                            } else {
                                $("<div/>").alert({
                                    title: TempoUtils.locale("mine.tooltip"),
                                    msg: TempoUtils.locale("sysheader.shanchushibai"),
                                });
                            }
                        }
                    });
                }
            }, {
                text: TempoUtils.locale("mine.publish-dialog-cancel"),
                id: 'tempo-sys-cancel-btn',
                click: function () {
                    Dialog.dialog("close");
                }
            }]
        })
    }

    /**
     * 提示信息
     * @param dialog
     */
    var themeTooltip = function (dialog) {
        var iconDiv = $("<div id='tooltip-icon' class='ui-icon tempo-ui-icon tempo-ui-icon-tip tempo-mine-button' style='margin-right: 35px;float: left;margin-top: 13px;cursor: pointer'>");
        //不知道哪个css给把标题样式改了
        var titleDiv = $(dialog.prev().children()[0]).css("width", "75px").css("font-size", "14px").css("font-weight", "bold");
        iconDiv.insertAfter(titleDiv);
        var tooltip = "<div id='theme-tooltip' style='background: #ffffff;" +
            "position:absolute;position:absolute;width:468px;height:40px;backgroud:#EAEDF1;" +
            "box-shadow:0px 0px 10px rgba(46,49,53,0.44);z-index:99999;text-align:left;padding: 6px 6px 6px 6px'>" +
            "<div>" + TempoUtils.locale("mine.theme-tip") + "</div>" +
            "<div>" + TempoUtils.locale("mine.tooltips") + "</div>";
        //判断只初始化一次
        if ($("#theme-tooltip").length == 0) {
            $('body').append(tooltip);
            $("#theme-tooltip").hide();
        }
        $("#tooltip-icon").mouseover(function () {
            var x = $("#tooltip-icon").offset().left;
            var y = $("#tooltip-icon").offset().top;
            $("#theme-tooltip").css("left", x + 20);
            $("#theme-tooltip").css("top", y + 20);
            $("#theme-tooltip").show();
        })
        $("#tooltip-icon").mouseout(function () {
            $("#theme-tooltip").hide();
        })
    }

    /**
     * 修改案例
     */
    var updateTheme = function (event, textTitle, data,id) {
        var dialog = $("<div/>", {
            'class': 'tempo-casebase-code-dialog—self'
        });
        dialog.dialog({
            modal: true,
            width: 760,
            height: 580,
            resizable: false,
            title: '编辑案例',
            open: function () {
                themeTooltip(dialog);
                $('.ui-dialog-title').css('width', '60px');
                $m.loadHtml(contextPath + "/api/ai/sysconfig/casebase/view/pub-self", dialog, undefined, data,function () {
                    window.updataTag = new Vue({
                        el: '#tag-list',
                        data: function () {
                            return {
                                value : [],
                                options: [],
                            }
                        },
                        mounted: function () {
                            this.getTagList();
                        },
                        methods: {
                            getTagList : function () {
                                var _this = this;
                                $.ajax({
                                    url: contextPath + "/api/ai/mine/tag/get-tag-by-templateids",
                                    data: {
                                        id:id
                                    },
                                    type: 'post',
                                    success: function (result) {
                                        if(result.success){
                                            _this.options = tagList;
                                            for (var i = 0; i < result.data.length; i++) {
                                                _this.value.push(result.data[i].value);
                                            }
                                        }
                                    }
                                });
                            },
                        },
                    })
                });
                $("#tempo-casebase-add-btn").hide();
                $("#tempo-casebase-up-btn").hide();
            },
            buttons: [{
                text: "下一步",
                id: 'tempo-casebase-next-btn',
                click: function () {
                    var $dom = $('#dialog-casebase-tempo').find('form');
                    $dom.find("input[name='appId']").val(data.appId);
                    //获取表单元素
                    var record = TempoUtils.getRecord($dom);
                    //回填渲染插件
                    TempoUtils.parserUi($dom, {});
                    //表单元素验证
                    var success = $dom.formValidate();
                    if (!success) {
                        return;
                    }
                    //判断上传文件是否为空加颜色
                    $.each($("input[type=file]"), function (n, m) {
                        var vule = m.value;
                        if (vule == "") {
                            $(this.parentElement).addClass("addBoxRed");
                        } else {
                            $(this.parentElement).removeClass("addBoxRed");
                        }
                        if (!vule) {
                            flage = false;
                        }
                    });
                    var flage = true;
                    $.each(dialog.find(".fimeName-text span"), function (n, m) {
                        var vule = $(this).text();
                        if (!vule) {
                            flage = false;
                        }
                    });
                    if (flage == false) {
                        $("#fileMsg").css("display", "block").text("附件文件不能为空!");
                    } else {
                        $("#fileMsg").css("display", "none");
                    }
                    if (dialog.find("#pdfSpan").text().length > 60) {
                        $("#fileMsg").css("display", "block").text("附件名称最大长度60,请修改!");
                        flage = false;
                    }
                    if (flage) {
                        index = 1;
                        ControlContent(index, dialog);
                        $("#tempo-casebase-next-btn").hide();
                        $("#tempo-casebase-up-btn").show();
                        $("#tempo-casebase-add-btn").show();
                        if(flagEventbus){
                            Eventbus.triggerHandler("renderPage.mine")
                            Eventbus.triggerHandler("initEvent.mine")
                        }
                    }
                    return flage;
                }
            }, {
                text: '上一步',
                id: 'tempo-casebase-up-btn',
                click: function () {
                    index = 0;
                    flagEventbus = false;
                    ControlContent(index, dialog);
                    $("#tempo-casebase-next-btn").show();
                    $("#tempo-casebase-up-btn").hide();
                    $("#tempo-casebase-add-btn").hide();
                }
            },
                {
                    text: '取消',
                    id: 'tempo-casebase-reset-btn',
                    click: function () {
                        flagEventbus = true;
                        dialog.dialog("destroy").remove();
                }
            },
                {
                    text: '保存',
                    id: 'tempo-casebase-add-btn',
                    click: function () {
                    flagEventbus = true;
                    var pro = $("<div/>").tempoprogressbar();
                    //获取表单中的案例数据
                    var $dom = $('#dialog-casebase-tempo').find('form');
                    if(window.updataTag.value.length > 0){
                        $dom.find("input[name='tagValue']").val(window.updataTag.value);
                    }
                    $dom.ajaxSubmit({
                        dataType: 'json',
                        type: 'post',
                        beforeSubmit: function (result) {
                            var obj = {};
                            obj.name = "category";
                            obj.value = $("#category").val();
                            obj.type = "select";
                            obj.required = false;
                            result.push(obj);
                            var obj1 = {};
                            obj1.name = "oldName";
                            obj1.value = data.name;
                            obj1.type = "input";
                            obj1.required = false;
                            result.push(obj1);
                            var flage = true;
                            $.each(dialog.find("input[type=file]"), function (n, m) {
                                var vule = m.value;
                                if (!vule) {
                                    $("#fileMsg").css("display", "block");
                                    $(this.parentElement).addClass("addBoxRed");
                                } else {
                                    $("#fileMsg").css("display", "none");
                                    $(this.parentElement).removeClass("addBoxRed");
                                }
                            });
                            $.each($(".uploadFile-btn"), function (j, k) {
                                if ($(this).css("display") == "block") {
                                    $("#fileMsg").text("附件文件不能为空!");
                                    flage = false;
                                }
                            });
                            if (!flage) {
                                pro.tempoprogressbar("destroy");
                            }
                            return flage;
                        },
                        //编辑案例时添加生成案例中 请稍后....
                        beforeSend: function () {
                            $("<div/>").alert({
                                width: 500,
                                height: 197,
                                msg: "正在生成案例中，请稍后...",
                            });
                        },
                        success: function (rs) {
                            pro.tempoprogressbar("destroy");
                            $("body").find('.tempo-alert-wrap').remove();
                            //清空筛选条件
                            tagId = "";
                            $("#tag-create-time").next().find("i.el-icon-caret-top").removeClass("icon-change-color");
                            $("#tag-create-time").next().find("i.el-icon-caret-bottom").removeClass("icon-change-color");
                            if(window.createSelectTag != undefined){
                                window.createSelectTag.tag = "";
                            }
                            if(window.searchTemplateName != undefined){
                                window.searchTemplateName.searchTemplate = '';
                            }
                            templateCurrentPage = 0;
                            if (rs.success) {
                                //获取权限勾选的权限数据
                                var builPermissionDatas = Eventbus.triggerHandler("builPermissionData.mine")[0];
                                //获取生成案例id
                                var resourceId = rs.data.code;
                                for (var i = 0; i < builPermissionDatas.length; i++) {
                                    //将id传递给授权信息中的resourceCode
                                    builPermissionDatas[i].resourceCode = resourceId;
                                }
                                if (builPermissionDatas.length == 0) {
                                    $("<div/>").alert({
                                        width: 500,
                                        height: 197,
                                        msg: "更新成功",
                                    });
                                }
                                if (builPermissionDatas.length > 0) {
                                    savePermission(builPermissionDatas, function (data) {
                                        $("<div/>").alert({
                                            width: 500,
                                            height: 197,
                                            msg: "更新成功",
                                        });
                                    });
                                }
                                dialog.dialog("destroy").remove();
                                // $(".tempo-alert").remove();
                                $("#tempo-template-list-self").empty();
                                listSelfTemplates();
                            } else {
                                if(rs.data == "tagIsNull"){
                                    $("#tempo-casebase-up-btn").click();
                                    initGetAllTag();
                                    window.updataTag.options = tagList;
                                    var array =[];
                                    for (var i = 0; i < window.updataTag.value.length; i++) {
                                        if(JSON.stringify(tagList).indexOf(window.updataTag.value[i]) != -1){
                                            array.push(window.updataTag.value[i]);
                                        }
                                    }
                                    window.updataTag.value = array;
                                }
                                $(".tempo-alert").remove();
                                $("<div/>").alert({
                                    msg: rs.message,
                                    title: TempoUtils.locale("mine.tooltip")
                                });
                            }
                        },
                        error: function () {
                            pro.tempoprogressbar("destroy");
                            $(".tempo-alert").remove();
                            dialog.dialog("destroy").remove();
                        }
                    });
                }
            }],
            close: function () {
                flagEventbus = true;
                dialog.dialog("destroy").remove();
            }
        })

    }

    /**
     * 发布为案例
     * @param data
     */
    var pubTheme = function (data) {
        var dialog = $("<div/>", {
            'class': 'tempo-casebase-code-dialog—self'
        });
        dialog.dialog({
            modal: true,
            width: 760,
            height: 580,
            resizable: false,
            title: "发布为案例",
            open: function () {
                themeTooltip(dialog);
                $m.loadHtml(contextPath + "/api/ai/sysconfig/casebase/view/pub-self", dialog, "",undefined,function () {
                    window.addTag = new Vue({
                        el: '#tag-list',
                        data: function () {
                            return {
                                value : [],
                                options: [],
                            }
                        },
                        mounted: function () {
                            this.getTagList();
                        },
                        methods: {
                            getTagList : function () {
                                var _this = this;
                                $.ajax({
                                    url: contextPath + '/api/ai/mine/tag/all-tag',
                                    method: 'POST',
                                    success: function(result) {
                                        if(result.success && result.data.length > 0){
                                            _this.options = result.data;
                                        }
                                    }
                                })
                            },
                        },
                    })
                });
                $("#tempo-casebase-add-btn").hide();
                $("#tempo-casebase-up-btn").hide();
            },
            buttons: [{
                text: "下一步",
                id: 'tempo-casebase-next-btn',
                click: function () {
                    var $dom = $('#dialog-casebase-tempo').find('form');
                    $dom.find("input[name='appId']").val(data.id);
                    //获取表单元素
                    var record = TempoUtils.getRecord($dom);
                    //回填渲染插件
                    TempoUtils.parserUi($dom, {});
                    //表单元素验证
                    var success = $dom.formValidate();
                    if (!success) {
                        return;
                    }
                    var flage = true;
                    $.each(dialog.find("input[type=file]"), function (n, m) {
                        var vule = m.value;
                        if (vule == "") {
                            $(this.parentElement).addClass("addBoxRed");
                        } else {
                            $(this.parentElement).removeClass("addBoxRed");
                        }
                        if (!vule) {
                            flage = false;
                        }
                    });
                    if (flage == false) {
                        $("#fileMsg").css("display", "block").text("附件文件不能为空!");
                    } else {
                        $("#fileMsg").css("display", "none");
                    }
                    if (dialog.find("#pdfSpan").text().length > 60) {
                        $("#fileMsg").css("display", "block").text("附件名称最大长度60,请修改!");
                        flage = false;
                    }
                    if (flage) {
                        index = 1;
                        ControlContent(index, dialog);
                        $("#tempo-casebase-next-btn").hide();
                        $("#tempo-casebase-up-btn").show();
                        $("#tempo-casebase-add-btn").show();
                        if(flagEventbusAdd){
                            Eventbus.triggerHandler("renderPage.mine")
                            Eventbus.triggerHandler("initEvent.mine")
                        }
                    }
                    return flage;
                }
            }, {
                text: '上一步',
                id: 'tempo-casebase-up-btn',
                click: function () {
                    flagEventbusAdd = false;
                    index = 0;
                    ControlContent(index, dialog);
                    $("#tempo-casebase-next-btn").show();
                    $("#tempo-casebase-up-btn").hide();
                    $("#tempo-casebase-add-btn").hide();
                }
            },
                {
                    text: '取消',
                    id: 'tempo-casebase-reset-btn',
                    click: function () {
                        flagEventbusAdd = true;
                        dialog.dialog("destroy").remove();
                }
            },
                {
                    text: '保存',
                    id: 'tempo-casebase-add-btn',
                    click: function () {
                    flagEventbusAdd = true;
                    var pro = $("<div/>").tempoprogressbar();
                    //获取表单中的案例数据
                    var $dom = $('#dialog-casebase-tempo').find('form');
                    if(window.addTag.value.length > 0){
                        $dom.find("input[name='tagValue']").val(window.addTag.value);
                    }
                    $dom.ajaxSubmit({
                        dataType: 'json',
                        type: 'post',
                        //生成案例时添加生成案例中 请稍后....
                        beforeSend: function () {
                            $("<div/>").alert({
                                width: 500,
                                height: 197,
                                msg: "正在生成案例中，请稍后...",
                            });
                        },
                        success: function (rs) {
                            pro.tempoprogressbar("destroy");
                            $("body").find('.tempo-alert-wrap').remove();
                            if (rs.success) {
                                //获取权限勾选的权限数据
                                var builPermissionDatas = Eventbus.triggerHandler("builPermissionData.mine")[0];
                                //获取生成案例id
                                var resourceId = rs.data.code;
                                for (var i = 0; i < builPermissionDatas.length; i++) {
                                    //将id传递给授权信息中的resourceCode
                                    builPermissionDatas[i].resourceCode = resourceId;
                                }
                                if (builPermissionDatas.length == 0) {
                                    $("<div/>").alert({
                                        width: 500,
                                        height: 197,
                                        msg: "发布成功",
                                    });
                                }
                                if (builPermissionDatas.length > 0) {
                                    savePermission(builPermissionDatas, function (data) {
                                        $("<div/>").alert({
                                            width: 500,
                                            height: 197,
                                            msg: "发布成功",
                                        });
                                    });
                                }
                                dialog.dialog("destroy").remove();
                                $(".tempo-alert").remove();
                                listSelfTemplates();
                            } else {
                                if(rs.data == "tagIsNull"){
                                    $("#tempo-casebase-up-btn").click();
                                    initGetAllTag();
                                    window.addTag.options = tagList;
                                    var array =[];
                                    for (var i = 0; i < window.addTag.value.length; i++) {
                                        if(JSON.stringify(tagList).indexOf(window.addTag.value[i]) != -1){
                                            array.push(window.addTag.value[i]);
                                        }
                                    }
                                    window.addTag.value = array;
                                }
                                $(".tempo-alert").remove();
                                $("<div/>").alert({
                                    msg: rs.message,
                                    title: TempoUtils.locale("mine.tooltip")
                                });
                            }
                        },
                        error: function () {
                            pro.tempoprogressbar("destroy");
                            $(".tempo-alert").remove();
                            dialog.dialog("destroy").remove();
                        }
                    });
                }
            }],
            close: function () {
                flagEventbusAdd = true;
                dialog.dialog("destroy").remove();	// 销毁弹出框,并返回
            }
        });
    }

    /**
     * 下一步 上一步事件
     * @type {number}
     */
    function ControlContent(index, dialog) {
        if (index == 1) {
            dialog.find('#dialog-casebase-tempo').addClass('main-hide');
            dialog.find('#point1').addClass('c-select');
            dialog.find('#line0').addClass('b-select');
            dialog.find('.poetry1').css("color", '#337BFF');
            dialog.find('.poetry2').css("color", '#337BFF');
            dialog.find('#tempo-mine-authorrization').css("display", "block");
            dialog.find('#tooltip').css("display", "block");
            dialog.find('#theme-tip').css("display", "none");
        } else if (index == 0) {
            dialog.find('#dialog-casebase-tempo').removeClass('main-hide');
            dialog.find('#point1').removeClass('c-select');
            dialog.find('#line0').removeClass('b-select');
            // dialog.find('.poetry1').css("color", '#333');
            dialog.find('.poetry2').css("color", '#333');
            dialog.find('#tempo-mine-authorrization').css("display", "none");
            dialog.find('#tooltip').css("display", "none");
            dialog.find('#theme-tip').css("display", "block");
        }
    }

    /**
     * 案例权限保存
     * @param data
     * @param callback
     */
    var savePermission = function (data, callback) {
        var that = this;
        var process = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + '/api/ai/resource/permission/modify',
            data: JSON.stringify(data),
            type: 'post',
            contentType: 'application/json',
            complete: function (XMLHttpRequest, textStatus) {
                process.tempoprogressbar("destroy");
            },
            success: function (resultData) {
                if (resultData.success) {
                    callback.call(that, resultData.data);
                } else {
                    $("<div/>").alert({
                        width: 500,
                        height: 197,
                        msg: resultData.message
                    });
                }
            }
        });
    }

    /**
     * 文件夹相关操作
     * @param data
     */
    var createFolder = function (data) {
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-hastree'
        });
        var height = 197;
        var folderName = "";
        var pid = "";

        if (data != null) {
            curFolderId = data.id;
            dialog.append("<div style='width:100%;height:100%;margin-top:10px'><form><span class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</span><input class='theme-open-dialog-input' type='text' id='createFolder'></form></div>");
        } else {
            curFolderId = "";
            height = 400;
            dialog.append("<div style='width:100%;height:100%;'><form><div class='theme_operate_create_folder'><span class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</span><input class='theme-open-dialog-input' type='text' id='createFolder'></form></div><div id='folderTreeDiv' class='theme_operate_folder_div'><div id='folderTree'></div></div></div>");
            openTree(dialog);
        }

        dialog.dialog({
            modal: true,
            width: 500,
            height: height,
            resizable: false,
            title: TempoUtils.locale("aidsview.folder_create2"),
            open: function () {
                var parentId = -1;
                if (data) {
                    parentId = data.parentId == null ? "-1" : data.id;
                }
                $.ajax({
                    url: contextPath + '/api/ai/resource/folder/work-name',
                    method: 'POST',
                    data: {
                        parentId: parentId,
                        prefix: "文件夹",
                        workSpaceId: $('.theme-container').attr("workspaceid")
                    },
                    success: function (result) {
                        dialog.find("#createFolder").val(result.data);
                    }
                });
            },
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var form = dialog.find("form");
                    if (!form.formValidate()) {
                        return;
                    }
                    folderName = dialog.find("input").val().trim();
                    pid = curFolderId;
                    var url = contextPath + '/api/ai/resource/folder/create';
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: {
                            parentId: pid,
                            name: folderName,
                            workSpaceId: $(".theme-container").attr('workspaceid')
                        },
                        success: function (rs) {
                            if (rs && rs.success) {
                                dialog.dialog("destroy").remove();
                                rs.data.fileType = 'FOLDER';
                                // 左侧资源树添加节点
                                rs.data.parentId = pid;
                                if (rs.data.parentId == "-1") {
                                    $themeTree.gtree("reload");
                                } else {
                                    $themeTree.gtree('addItem', rs.data, pid);
//									$themeTree.gtree('clickItem', rs.data.id);
                                }
                            } else {
                                failTip(rs.message);
                            }
                            progressbar.tempoprogressbar("destroy");
                        }
                    })
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        nameValid(dialog.find("#createFolder"));
    }

    var deleteFolder = function (data, tag) {
        var folderid = data.id;
        $("<div>").confirm({
            width: 500,
            height: 197,
            msg: TempoUtils.locale("aidsview.delete_tip"),
            ok: function () {
                var url = contextPath + '/api/ai/resource/folder/delete';
                if (tag && tag == "pub") {
                    url = contextPath + '/api/ai/resource/pub-folder/delete';
                }
                $.ajax({
                    url: url,
                    method: 'POST',
                    data: {
                        id: folderid
                    },
                    success: function (data) {
                        if (data && data.success) {
                            if (tag && tag == "pub") {
                                $pubThemeTree.gtree('removeItem', folderid);
                            } else {
                                $themeTree.gtree('removeItem', folderid);
                            }
                        } else {
                            failTip(data.message);
                        }
                    }
                })
            }
        });
    }

    var createTheme = function (data, tag) {
        curFolderId = "";
        var folderId = "";
        var themeName = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-hastree'
        });
        var height = 260;

        if (data != null) {
            curFolderId = data.id;
            dialog.append("<div style='width:100%;height:100%;'><form><table><tr><td><label class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</label></td><td><input type='text' id='createTheme' ></td></tr><tr><td><label class='theme_operate_input_name'>" + TempoUtils.locale("aidsview.description") + "</label></td><td><textarea  placeholder='" + TempoUtils.locale("aidsview.max_200_char") + "' style='height:80px;resize:none;' id='themeDescription'></textarea></td></tr></table></form></div>");
        } else {
            height = 440
            openTree(dialog);
            dialog.append("<div style='width:100%;height:100%;'><form><table><tr><td><label class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</label></td><td><input type='text' id='createTheme' ></td></tr><tr><td><label class='theme_operate_input_name'>" + TempoUtils.locale("aidsview.description") + "</label></td><td><textarea  placeholder='" + TempoUtils.locale("aidsview.max_200_char") + "' style='height:40px;resize:none;' id='themeDescription'></textarea></td></tr></table></form><div id='folderTreeDiv'><div id='folderTree'></div></div></div>");
        }
        dialog.dialog({
            modal: true,
            width: 500,
            height: height,
            resizable: false,
            title: TempoUtils.locale("aidsview.theme_create"),
            open: function () {
                var parentId = -1;
                if (data) {
                    parentId = data.parentId == null ? "-1" : data.id;
                }
                $.ajax({
                    url: contextPath + '/api/ai/resource/analyse/list-allapp',
                    method: 'POST',
                    data: {
                        folderId: parentId,
                        prefix: "应用",
                        description: "",
                        workSpaceId: $('.theme-container').attr("workspaceid")
                    },
                    success: function (result) {
                        dialog.find("#createTheme").val(result.data);
                    }
                });
            },
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var form = dialog.find("form");
                    if (!form.formValidate()) {
                        return;
                    }
                    folderId = curFolderId;
                    themeName = dialog.find("input").val();
                    var desc = dialog.find("#themeDescription").val();
                    var url = contextPath + '/api/ai/resource/analyse/create';
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: {
                            folderId: folderId,
                            name: themeName,
                            description: desc,
                            workSpaceId: $(".theme-container").attr('workspaceid')
                        },
                        success: function (rs) {
                            if (rs && rs.success) {
                                rs.data.fileType = 'FILE';
                                rs.data.belong = '1';
                                // 父id需要重新赋值，这里取folderId
                                rs.data.parentId = rs.data.folderId;
                                if ($(".theme-container").attr("workspacetype") != "self" && rs.data.parentId == "-1") {
                                    // 工作空间根目录下新建
                                    $themeTree.gtree('loadAndSelectItem', rs.data, null);
                                } else {
                                    $themeTree.gtree('loadAndSelectItem', rs.data, rs.data.folderId);
                                }
                                dialog.dialog("destroy").remove();
                                editTheme(rs.data);
                            } else {
                                failTip(rs.message);
                            }
                            progressbar.tempoprogressbar("destroy");
                        }
                    })
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        nameValid(dialog.find("#createTheme"));
        descValid(dialog.find("#themeDescription"));
    }

    var importTheme = function (data, tag) {
        var folderId = "";
        var id = data.id;
        if (data.fileType && data.fileType == "FOLDER") {
            folderId = data.id;
            id = folderId
        } else {
            if ($themeTree.gtree("getSelected") != null && $themeTree.gtree("getSelected").fileType == "FOLDER") {
                folderId = $themeTree.gtree("getSelected").id
                id = folderId
            } else {
                // 未选中文件夹
                folderId = -1;
                if ($themeContainer.attr("workspacetype") == 'self') {
                    id = -1;
                }
            }
        }

        var form = $("#tempo-mining-import-app-form");
        form.find('input[name="id"]').val(id);
        form.find('input[name="themeId"]').val(id);
        form.find('input[name="folderId"]').val(folderId);
        form.find('input[name="workSpaceId"]').val($themeContainer.attr("workspaceid"));

        var uploadFileBtn = $("#tempo-mining-import-app-button");
        uploadFileBtn.unbind("change").bind("change", function (e) {
            importFileSubmit(form, $(this), data);
            // 清空之前文件
            e.target.value = "";
        });
        uploadFileBtn[0].click();
    }

    var importFileSubmit = function (form, uploadFileBtn, data) {
        var folderId = form.find('input[name="folderId"]').val();
        var id = form.find('input[name="id"]').val()

        var file = uploadFileBtn[0].files[0];
        var fileSize = file.size;
        if (fileSize <= 0) {
            $("<div/>").alert({
                msg: TempoUtils.locale("aidsview.empty_file_not_export"),
                ok: function () {
                    $("#tempo-mining-import-app-form")[0].reset();
                }
            });
            return;
        }
        var fileName = file.name;
        if (!fileName.endsWith('.tapp') && !fileName.endsWith('.zip')) {
            $("<div/>").alert({
                msg: TempoUtils.locale("aidsview.theme_import_tip"),
                ok: function () {
                    $("#tempo-mining-import-app-form")[0].reset();
                }
            });
            return;
        }
        var progressbar = $("<div/>").tempoprogressbar();
        form.ajaxSubmit({
            dataType: 'json',
            type: 'post',
            beforeSubmit: function (result) {
                return true;
            },
            success: function (rs) {
                if (rs && rs.success) {
                    rs.data.fileType = 'FILE';
                    rs.data.belong = '1';
                    // 父id需要重新赋值，这里取folderId
                    rs.data.parentId = rs.data.folderId;
                    $themeTree.gtree('addItem', rs.data, id);
                    $themeTree.gtree('clickItem', rs.data.id);
                } else {
                    failTip(rs.message);
                }
                progressbar.tempoprogressbar("destroy");
            },
            complete: function () {
            },
            error: function (e) {
                if(e.status == 413){
                    failTip("应用文件过大，导入失败！");
                }else{
                    failTip(TempoUtils.locale("aidsview.import_theme_fail"));
                }
                progressbar.tempoprogressbar("destroy");
            }
        });
    }

    var nameValid = function (e) {
        e.attr("ui-role", "validatebox");
        e.validatebox({
//			valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/],
            required: true,
            maxLength: 60,
            autofill: false,
            tip: TempoUtils.locale("aidsview.nameValid"),
        })
    }

    var createThemeNameByTemolateValid = function (e) {
        e.attr("ui-role", "validatebox");
        e.validatebox({
//			valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/],
            required: true,
            maxLength: 200,
            autofill: false,
            tip: TempoUtils.locale("此项为必填项，最大长度为200"),
        })
    }
    var descValid = function (e) {
        e.attr("ui-role", "validatebox");
        e.validatebox({
            maxLength: 200,
            autofill: false,
            tip: TempoUtils.locale("aidsview.description_tip"),
        })
    }

    /**
     * AI关联BI图标点击事件
     */
    var initAiRelationBi = function () {
        $aiRelationBi.unbind('click').bind('click', function () {
            /**
             * 定义储存aibi关联的信息
             * relationAndAllowBiInfo 当前用户允许的bi空间信息，包括空间名称和应用名称
             * relationAllBiInfo 已经关联的BI信息，不包含空间名称和应用名称
             * noAllowRelationBiInfo 不允许的关联信息
             */
            var relationAllData = {};
            var $aiRelationBiDialog = $('<div>').dialog({
                width: 586,
                height: 500,
                // 开启遮罩  modal 不是 model 是a不是e
                modal: true,
                resizable: false,
                title: '数据可视化',
                close: function () {
                    $aiRelationBiDialog.dialog('destroy').remove();
                },
                open: function () {
                    openAiRelationBiDialog($(this), relationAllData);
                },
                buttons: [
                    {
                        text: TempoUtils.locale("mine.guanbi"),
                        click: function () {
                            $aiRelationBiDialog.dialog('close');
                        }
                    }
                ]
            }).addClass("tempo-ai-relation-tempo-bi-dialog");
        })
    };

    /**
     * 初始化AI关联BI页面
     * @param thisDialog 当前弹框 jquery对象
     * @param relationAllData 依赖所需要的全部数据
     */
    var openAiRelationBiDialog = function (thisDialog, relationAllData) {

        //
        /**
         * 初始化事件
         * @param $biAppInfoDiv bi信息所在的div
         * @param openDblclick 是否开启双击事件
         * @param openHoverEnven 是否开启鼠标移入事件
         */
        var initRelationBiInfoEvent = function ($biAppInfoDiv, openDblclick, openHoverEnven) {
            if (openHoverEnven) {
                // bi信息div 鼠标移入/移除 显示/隐藏删除按钮
                $biAppInfoDiv.hover(
                    function () {
                        // 留在div上，显示删除按钮
                        $biAppInfoDiv.find('.tempo-relation-bi-info-right').show();
                        $biAppInfoDiv.css('box-shadow', '0px 3px 3px #ebebe4');
                        $biAppInfoDiv.css('-moz-box-shadow', '0px 3px 3px #ebebe4');
                        $biAppInfoDiv.css('-webkit-box-shadow', '0px 3px 3px #ebebe4');
                    },
                    function () {
                        // 离开元素，隐藏删除按钮
                        $biAppInfoDiv.find('.tempo-relation-bi-info-right').hide();
                        $biAppInfoDiv.css('box-shadow', '0px 0px 0px #ebebe4');
                        $biAppInfoDiv.css('-moz-box-shadow', '0px 0px 0px #ebebe4');
                        $biAppInfoDiv.css('-webkit-box-shadow', '0px 0px 0px #ebebe4');
                    }
                );
            }

            if (openDblclick) {
                // bi信息div 双击事件
                $biAppInfoDiv.unbind('dblclick').bind('dblclick', function () {
                    // 获取Bi信息
                    var needSkipBiInfo = $biAppInfoDiv.data('biInfo');
                    // window.open(contextPath + "/api/ai/resource/skip-bi-design-page?biAppId=" + needSkipBiInfo.BI_APP_ID);
                    window.open("/tempo-bi-design/api/bi/resource/analyse/view/index?id=" + needSkipBiInfo.BI_APP_ID, "");
                    // window.openUrlPost(contextPath + "/api/ai/resource/skip-bi-design-page", {biAppId: needSkipBiInfo.BI_APP_ID}, "_blank")
                });
            }

            // 删除按钮 删除事件
            $biAppInfoDiv.find('.tempo-relation-delete-div').unbind('click').bind('click', function () {
                // 获取Bi信息
                var needDeleteAiBiRelationInfo = $biAppInfoDiv.data('biInfo');
                $biAppInfoDiv.remove();
                thisDialog.find('.tempo-ai-add-tempo-bi-number').html(thisDialog.find('.tempo-ai-add-tempo-bi-number').html() - 1);
                $.ajax({
                    url: contextPath + '/api/ai/resource/delete-ai-bi-relation-info?relationId=' + needDeleteAiBiRelationInfo.RELATION_ID,
                    type: 'get',
                    success: function (response) {
                        if (response.success && response.data) {
                            // 代表成功
                        }
                    }
                });
            });
        };

        // 需要获取已经关联的BI信息
        $.ajax({
            url: contextPath + '/api/ai/resource/get-relation-bi-info?aiWorkspaceId=' + workSpaceId + '&aiAppId=' + theme.id,
            type: 'get',
            async: false,
            success: function (response) {
                relationAllData.relationAllBiInfo = [];
                if (response.success && response.data) {
                    relationAllData.relationAllBiInfo = response.data;
                }
            },
            error: function (error) {
                failTip(error.responseJSON.message);
            }
        });

        // 获取已经关联的并且当前用户允许的BI空间信息
        $.ajax({
            url: contextPath + '/api/ai/resource/get-relation-and-allow-bi-info?aiWorkspaceId=' + workSpaceId + '&aiAppId=' + theme.id,
            type: 'get',
            async: false,
            success: function (response) {
                relationAllData.relationAndAllowBiInfo = [];
                if (response.success && response.data) {
                    relationAllData.relationAndAllowBiInfo = response.data;
                }
            },
            error: function (error) {
                failTip(error.responseJSON.message);
            }
        });

        // 对比获取不允许的关联信息
        relationAllData.noAllowRelationBiInfo = [];
        // 将已经关联的并且当前用户允许的BI空间信息中的BI应用id转化为array
        var biAppIdArray = [];
        var relationAndAllowBiInfoLen = relationAllData.relationAndAllowBiInfo.length;
        for (var i = 0; i < relationAndAllowBiInfoLen; i++) {
            biAppIdArray.push(relationAllData.relationAndAllowBiInfo[i].BI_APP_ID);
        }
        var relationBiInfoLen = relationAllData.relationAllBiInfo.length;
        for (var i = 0; i < relationBiInfoLen; i++) {
            if (biAppIdArray.indexOf(relationAllData.relationAllBiInfo[i].BI_APP_ID) == -1) {
                // 判断应用是否存在，并获取空间和应用信息
                $.ajax({
                    url: contextPath + '/api/ai/resource/get-bi-info-by-bi-app-id?biAppIp=' + relationAllData.relationAllBiInfo[i].BI_APP_ID,
                    type: 'get',
                    async: false,
                    success: function (response) {
                        if (response.success && response.data) {
                            // 判断是否有值
                            if (response.data.length == 0) {
                                relationAllData.relationAllBiInfo[i].IS_EXIST = false;
                            } else {
                                // 将bi的空间名称和应用名称存进去
                                relationAllData.relationAllBiInfo[i].BI_APP_NAME = response.data[0].BI_APP_NAME;
                                relationAllData.relationAllBiInfo[i].BI_WORKSPACE_NAME = response.data[0].BI_WORKSPACE_NAME;
                                relationAllData.relationAllBiInfo[i].IS_EXIST = true;
                            }
                            // 将信息存起来
                            relationAllData.noAllowRelationBiInfo.push(relationAllData.relationAllBiInfo[i]);
                        }
                    },
                    error: function (error) {
                        failTip(error.responseJSON.message);
                    }
                });
            }
        }

        // 画页面头部
        $("<div class='tempo-ai-relation-tempo-bi-body'>\n" +
            "   <div class='tempo-ai-relation-tempo-bi-head'>\n" +
            "     <div class='tempo-ai-bi-head-left'>\n" +
            "       <label>已添加应用</label>\n" +
            "       <span class='tempo-ai-add-tempo-bi-number'>" + relationAllData.relationAllBiInfo.length + "</span>\n" +
            "     </div>\n" +
            "     <div class='tempo-ai-bi-head-right'>\n" +
            "       <button class='tempo-add-relation-bi-button'><span class='tempo-relation-add-sign ui-icon tempo-ui-icon tempo-ui-icon-blue-add'></span>添加应用</button>\n" +
            "     </div>\n" +
            "   </div>\n" +
            "   <div class='tempo-ai-relation-tempo-bi-center'></div>\n" +
            "</div>").appendTo(thisDialog);

        var $biAppInfoBlock = thisDialog.find(".tempo-ai-relation-tempo-bi-center");

        // 先画当前用户有权限的
        for (var i = 0; i < relationAndAllowBiInfoLen; i++) {
            var tmpRelationAndAllowBiInfo = relationAllData.relationAndAllowBiInfo[i];
            // 画bi应用部分
            var $biAppInfoDiv = $("<div class='tempo-relation-bi-info-div'>\n" +
                "   <div class='tempo-relation-bi-info-blue-bar'></div>\n" +
                "   <div class='tempo-relation-bi-info-left'>\n" +
                "       <div class='tempo-relation-bi-workspace-info-div'>\n" +
                "           <span class='ui-icon tempo-ui-icon tempo-ui-icon-small-workspace'></span>\n" +
                "           <span class='tempo-relation-bi-workspace-name' title='" + tmpRelationAndAllowBiInfo.BI_WORKSPACE_NAME + "'>" + tmpRelationAndAllowBiInfo.BI_WORKSPACE_NAME + "</span>\n" +
                "       </div>\n" +
                "       <div class='tempo-relation-bi-app-info-div'>\n" +
                "           <span class='tempo-relation-bi-app-icon ui-icon tempo-ui-icon tempo-ui-icon-small-app'></span>\n" +
                "           <span class='tempo-relation-bi-app-name' title='" + tmpRelationAndAllowBiInfo.BI_APP_NAME + "'>" + tmpRelationAndAllowBiInfo.BI_APP_NAME + "</span>\n" +
                "       </div>\n" +
                "   </div>\n" +
                "   <div class='tempo-relation-bi-info-right'>\n" +
                "       <span class='tempo-relation-delete-div ui-icon tempo-ui-icon tempo-ui-icon-search-clean'></span>\n" +
                "   </div>\n" +
                "</div>").appendTo($biAppInfoBlock);
            $biAppInfoDiv.data('biInfo', tmpRelationAndAllowBiInfo);
            // 绑定事件
            initRelationBiInfoEvent($biAppInfoDiv, true, true);

        }
        // 后画当前用户没有权限的
        var noAllowRelationBiInfoLen = relationAllData.noAllowRelationBiInfo.length;
        for (var i = 0; i < noAllowRelationBiInfoLen; i++) {
            var tmpNoAllowRelationBiInfo = relationAllData.noAllowRelationBiInfo[i];
            // 画存在但没有权限的bi应用
            if (tmpNoAllowRelationBiInfo.IS_EXIST) {
                // 画bi应用部分
                var $biAppInfoDiv = $("<div class='tempo-relation-bi-info-div'>\n" +
                    "   <div class='tempo-relation-bi-info-blue-bar'></div>\n" +
                    "   <div class='tempo-relation-bi-info-left'>\n" +
                    "       <div class='tempo-relation-bi-workspace-info-div'>\n" +
                    "           <span class='ui-icon tempo-ui-icon tempo-ui-icon-small-workspace'></span>\n" +
                    "           <span class='tempo-relation-bi-workspace-name' title='" + tmpNoAllowRelationBiInfo.BI_WORKSPACE_NAME + "'>" + tmpNoAllowRelationBiInfo.BI_WORKSPACE_NAME + "</span>\n" +
                    "       </div>\n" +
                    "       <div class='tempo-relation-bi-app-info-div'>\n" +
                    "           <span class='tempo-relation-bi-app-icon ui-icon tempo-ui-icon tempo-ui-icon-small-app'></span>\n" +
                    "           <span class='tempo-relation-bi-app-name' title='" + tmpNoAllowRelationBiInfo.BI_APP_NAME + "'>" + tmpNoAllowRelationBiInfo.BI_APP_NAME + "</span>\n" +
                    "       </div>\n" +
                    "   </div>\n" +
                    "   <div class='tempo-relation-bi-info-right'>\n" +
                    "       <span class='tempo-relation-delete-div ui-icon tempo-ui-icon tempo-ui-icon-search-clean'></span>\n" +
                    "   </div>\n" +
                    "</div>").appendTo($biAppInfoBlock);
                $biAppInfoDiv.data('biInfo', tmpNoAllowRelationBiInfo);
                $biAppInfoDiv.css("background-color", "#ebebe4");
                // 绑定事件
                initRelationBiInfoEvent($biAppInfoDiv, false, false);
            }
            // 画已删除的bi应用，此功能已被砍掉，改为直接删除
            if (!tmpNoAllowRelationBiInfo.IS_EXIST && false) {
                // 画bi应用部分
                var $biAppInfoDiv = $("<div class='tempo-relation-bi-info-div'>\n" +
                    "   <div class='tempo-relation-bi-info-blue-bar'></div>\n" +
                    "   <div class='tempo-relation-bi-info-left'>\n" +
                    "       <div class='tempo-relation-bi-workspace-info-div'>\n" +
                    "           <span class='tempo-relation-bi-workspace-name' title='已删除'>已删除</span>\n" +
                    "       </div>\n" +
                    "   </div>\n" +
                    "   <div class='tempo-relation-bi-info-right'>\n" +
                    "       <sapn class='tempo-relation-delete-div ui-icon tempo-ui-icon tempo-ui-icon-search-clean'></sapn>\n" +
                    "   </div>\n" +
                    "</div>").appendTo($biAppInfoBlock);
                $biAppInfoDiv.data('biInfo', tmpNoAllowRelationBiInfo);
                $biAppInfoDiv.css("background-color", "#ebebe4");
                // 绑定事件
                initRelationBiInfoEvent($biAppInfoDiv, false, false);
            }
            if (!tmpNoAllowRelationBiInfo.IS_EXIST) {
                // 删除已经删除的bi应用
                thisDialog.find('.tempo-ai-add-tempo-bi-number').html(thisDialog.find('.tempo-ai-add-tempo-bi-number').html() - 1);
                $.ajax({
                    url: contextPath + '/api/ai/resource/delete-ai-bi-relation-info?relationId=' + tmpNoAllowRelationBiInfo.RELATION_ID,
                    type: 'get',
                    success: function (response) {
                        if (response.success && response.data) {
                            // 代表成功
                        }
                    }
                });
            }
        }

        // 为添加应用按钮绑定事件
        thisDialog.find('.tempo-add-relation-bi-button').unbind('click').bind('click', function () {
            $m.loadHtml(contextPath + '/api/ai/app/view/add-bi-app-relation?aiWorkspaceId=' + workSpaceId + '&aiAppId=' + theme.id, $('body'), 'tempo-app-add-achievement-dialog', {
                callback: function (selectData) {
                    // 构造保存的数据集
                    var saveRealtionData = [];
                    var selectDataLen = selectData.length;
                    for (var i = 0; i < selectDataLen; i++) {
                        var tmpSaveRelation = {
                            relationId: TempoUtils.uuid(),
                            aiWorkSpaceId: workSpaceId,
                            aiAppId: theme.id,
                            aiFlowId: null,
                            biWorkSpaceId: selectData[i].workSpaceId,
                            biAppId: selectData[i].id,
                            biSouceId: null,
                            relationTimestamp: DateUtils.getCurrentDate().getTime(),
                            relationSign: 1,
                            remark: null
                        }
                        saveRealtionData.push(tmpSaveRelation);
                    }
                    $.ajax({
                        url: contextPath + '/api/ai/resource/save-ai-relation-bi-data',
                        type: 'post',
                        async: false,
                        data: {
                            saveRealtionData: JSON.stringify(saveRealtionData)
                        },
                        success: function (response) {
                            if (response.success && response.data) {
                                // 将关联弹框清空
                                thisDialog.empty();
                                // 重新渲染
                                openAiRelationBiDialog(thisDialog, relationAllData);
                            }
                        },
                        error: function (error) {
                            failTip(error.responseJSON.message);
                        }
                    });
                }
            });
        });
    };

    this.init = function () {
        Vue.use(httpVueLoader);
        Vue.config.warnHandler = function(warn) {
            return "";
        };
        hideTemplate();
        layout();
        toolbar();
        setWorksapceList.init();
        initTabs();
        initSearchbar();
        addThemeToobarSelectClass($editBtn);
        initCreateBtn();
        bindUpdateNameButton();
        initTreeSortButton();
        initEventBus();
        initAiRelationBi();
        // 选中第一个
        $themeTabs.children("li:first-child").trigger("click");
        //修改发布空间-右侧按钮的样式，使其在1366分辨率下显示
        $createTaskBtn.parent().children().css("margin-right", "5px;").css("width", "68px").css("padding", "0 8px");
    };

    var initGetAllTag = function () {
        // 获取所有标签
        $.ajax({
            url: contextPath + '/api/ai/mine/tag/all-tag',
            type: 'post',
            async: false,
            success: function (result) {
                if(result.success){
                    tagList = result.data;
                }
            },
        });
    }

    //创建时间按钮绑定事件
    var createTagTime = function () {
        //案例库页面展示更新时间
        $(".tempo-case-tag-create-time").css("display","block");
        var iconTop = $("#tag-create-time").next().find("i.el-icon-caret-top");
        var iconBottom = $("#tag-create-time").next().find("i.el-icon-caret-bottom");
        iconTop.css("left",$("#tag-create-time").offset().left-178);
        iconBottom.css("left",$("#tag-create-time").offset().left-178);
        $("#tag-create-time").unbind('click').bind('click', function () {
            if(iconTop.hasClass("icon-change-color")){
                iconTop.removeClass("icon-change-color");
                iconBottom.addClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }
            }else if(iconBottom.hasClass("icon-change-color")){
                iconTop.removeClass("icon-change-color");
                iconBottom.removeClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0);
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0);
                }
            }else {
                iconTop.addClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"asc");
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"asc");
                }
            }
        });
        iconTop.unbind('click').bind('click', function () {
            if(iconBottom.hasClass("icon-change-color")){
                iconBottom.removeClass("icon-change-color");
            }
            if(iconTop.hasClass("icon-change-color")){
                iconTop.removeClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }
            }else {
                iconTop.addClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"asc");
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"asc");
                }
            }
        });
        iconBottom.unbind('click').bind('click', function () {
            if(iconTop.hasClass("icon-change-color")){
                iconTop.removeClass("icon-change-color");
            }
            if(iconBottom.hasClass("icon-change-color")){
                iconBottom.removeClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0);
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0);
                }
            }else {
                iconBottom.addClass("icon-change-color");
                if(templateFlag == "template-config-public"){
                    listAllTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }else if(templateFlag == "template-config-self"){
                    listSelfTemplates(tagId,window.searchTemplateName.searchTemplate,30,0,"desc");
                }
            }
        });
    }

    var initSelectMenu = function () {
        createTagTime();
        if(window.createSelectTag == undefined){
            window.createSelectTag = new Vue({
                el: '#case-select',
                data: function () {
                    return {
                        tag : "",
                        options: [],
                    }
                },
                mounted: function () {
                    this.getTagList();
                },
                methods: {
                    getTagList : function () {
                        var _this = this;
                        _this.options = tagList;
                    },
                    selectTag: function () {
                        var _this = this;
                        tagId = _this.tag;
                        var text = window.searchTemplateName.searchTemplate;
                        var iconTop = $("#tag-create-time").next().find("i.el-icon-caret-top");
                        var sort = "";
                        if(iconTop.hasClass("icon-change-color")){
                            sort = "asc";
                        }else {
                            sort = "desc";
                        }
                        // 通过标签筛选所有公共案例
                        if(templateFlag == "template-config-public"){
                            listAllTemplates(tagId,text,30,0,sort)
                        }
                        // 通过标签筛选所有私有案例
                        if(templateFlag == "template-config-self"){
                            listSelfTemplates(tagId,text,30,0,sort);
                        }
                    },
                    clickTag: function () {
                        // 获取所有标签
                        $.ajax({
                            url: contextPath + '/api/ai/mine/tag/all-tag',
                            type: 'post',
                            async: false,
                            success: function (result) {
                                if(result.success){
                                    tagList = result.data;
                                    window.createSelectTag.options = tagList;
                                }
                            },
                        });
                    }
                },
            })
        }else {
            //清空筛选条件
            tagId = "";
            $("#tag-create-time").next().find("i.el-icon-caret-top").removeClass("icon-change-color");
            $("#tag-create-time").next().find("i.el-icon-caret-bottom").removeClass("icon-change-color");
            window.createSelectTag.tag = "";
        }
    }

    var initCreateBtn = function () {
        $("#ai-create-project").click(function () {
            createTheme();
        })
        //基于案例创建按钮绑定点击事件
        $("#ai-create-case").click(function () {
            showTemplate();
            initSelectMenu();
        })
        $("#createWorkspace").click(function () {
            var data = []
            var $this = $(this);
            if ($this.parent().hasClass("ui-state-disabled")) {
                return
            }
            var offset = $this.offset()
            var contextMenu = getContextMenu({type: "rootnode"}, 0);
            var top = offset.top;
            var menuHeight = contextMenu.outerHeight();
            if (top + menuHeight > window.innerHeight) {
                top = top - menuHeight;
            }
            contextMenu.contextmenu("show", {
                position: {
                    left: offset.left + $this.width() / 2 + 14,
                    top: top
                },
                linkEl: {
                    data: data
                }
            })
        })


        $('body').mouseout(function (e) {
            if (!$(e.target).closest("#workspace-select,#tempo_workspace_index,#tempo_workspace_select").length) {
                $(".workspace-ul").hide();
            }
        })
        $('body').click(function (e) {
            if (!$(e.target).closest("#workspace-select,#tempo_workspace_index,#tempo_workspace_select").length) {
                $(".workspace-ul").hide();
            }
        })
    }

    var createSelectLi = function (menus) {
        var $WorkspaceSelectDiv = $("#tempo_workspace_select");
        var $WorkspaceIndexDiv = $("#tempo_workspace_index");
        for (var j = 0; j < menus.length; j++) {
            if (menus[j].id == workSpaceId) {
                workspceName = menus[j].text;
            }
            $("<li>", {
                value: menus[j].id,
                text: _subString(menus[j].text, 13),
            }).data('ds-item', menus[j]).attr('title', menus[j].text).appendTo($WorkspaceSelectDiv);
        }
        ;
        $("<li>", {
            'class': 'workspace-index',
            value: 'workspaceIndex',
            text: "空间管理",
        }).data('ds-item', menus[j]).appendTo($WorkspaceIndexDiv);


    }

    var getWorkSpaceList = function () {
        var menus = [];
        $.ajax({
            url: contextPath + ('/api/ai/workspace/list'),
            type: 'post',
            data: {
                fType: fType,
                searchName: '',
                Type: ""
            },
            async: false,
            dataType: 'json',
            success: function (result) {
                var objs = result.data;
                objs.sort(sortRule);
                for (var i = 0; i < objs.length; i++) {
                    if (objs[i].ID == $themeContainer.attr("workspaceid")) {
                        $themeContainer.attr("workspacetype", objs[i].WORK_SPACE_TYPE);
                    }
                    menus.push({
                        text: objs[i].NAME,
                        id: objs[i].ID,
                    })
                }
            }
        });
        return menus;
    }

    /**
     * 上一个方法里使用的排序规则
     * 比较收藏时间的前后顺序
     * @param a 元素第n个
     * @param b 元素第n+1个
     * @returns {number}
     */
    function sortRule(a, b) {
        return b.NOWTIME - a.NOWTIME;
    }

    var _subString = function (str, length) {
        if (!str) return "";
        var chRegex = /[^\x00-\xff]/g;
        var newLength = 0;
        var newStr = "";
        var strLength = str.replace(chRegex, "**").length;
        if (strLength < length) {
            return str;
        }
        for (var i = 0; i < strLength; i++) {
            var singleChar = str.charAt(i);
            if (singleChar.match(chRegex) != null) {
                newLength += 2;
            } else {
                newLength++;
            }
            if (newLength > length) {
                break;
            }
            newStr += singleChar;
        }
        return newStr += "...";
    }

    /**
     * 设置工作空间列表
     */
    var setWorksapceList = (function () {
        var menus = getWorkSpaceList();
        $('#workspace-select').html('<ul id="tempo_workspace_index" class="workspace-ul"></ul>' +
            '<ul id="tempo_workspace_select" class="workspace-ul"></ul>');
        var $WorkspaceSelectDiv = $("#tempo_workspace_select");
        var $WorkspaceIndexDiv = $("#tempo_workspace_index");
        createSelectLi(menus);
        var contextMenu, click, init, select, workspceName;
        for (var j = 0; j < menus.length; j++) {
            if (menus[j].id == workSpaceId) {
                workspceName = menus[j].text;
            }
        }
        var inputHtml = "<span type='text' id='change_select' readonly unselectable='on' class='select-input'></span>"
        $WorkspaceIndexDiv.css({'top': $WorkspaceSelectDiv.height()});
        $('#workspace-select').append(inputHtml)
        $(".select-input").text(_subString(workspceName, 14)).attr('title', workspceName);
        $("#change_select").on("click", function () {
            var thisul = $(".workspace-ul")
            var thisInput = $(".select-input")
            if ($(".select-option").css('display') == "block") {
                $(".select-option").hide();
            }
            if (thisul.css('display') == "none") {
                $WorkspaceSelectDiv.find("li").remove();
                $WorkspaceIndexDiv.find("li").remove();
                createSelectLi(getWorkSpaceList());
                $WorkspaceIndexDiv.css({'top': $WorkspaceSelectDiv.height() + 16});
                thisul.show();
                thisul.find('li').click(function () {
                    thisInput.text($(this).text());
                    select($(this).attr('value'))
                    thisul.hide();
                }).hover(function () {
                    $(this).addClass("hover");
                }, function () {
                    $(this).removeClass("hover");
                });
            } else {
                thisul.hide();
            }
            ;
        });
        click = function (e) {
        };
        select = function (id) {
            var thisUrl = contextPath + "/api/" + (fType == "mining" ? "ai" : "bi") + "/resource/view/theme?workSpaceId=" + id;
            if (id == "workspaceIndex") {
                thisUrl = contextPath + "/api/" + (fType == "mining" ? "ai" : "bi") + "/resource/view/workspace?enterType=theme";
            }
            thisUrl = TempoUtils.addHideIconParam(thisUrl);
            window.location.href = thisUrl;
        }
        init = function () {
            $WorkspaceSelectDiv.bind("click", click);
        }
        return {
            init: init
        }
    })();

    /**
     * 初始化Eventbus
     */
    var initEventBus = function () {
        // 发布或者取消发布重新刷发布区的树
        // 设计区发布/取消发布/同步操作通知
        Eventbus.bind("reloadPubTree.ai-theme", pubtreeReload, this);
        // 服务名称同步
        Eventbus.bind("updateName.service", pubtreeNameUpdate, this);
        Eventbus.bind("updateserviceStatus.service", serviceStatusUpdate, this);

        //授权之后页面授权人数刷新
        Eventbus.bind("permission.theme", permissionUser, this);

        //发布、取消发布后通知已发布场景数量刷新
        Eventbus.bind("publishNum.theme", loadPublishNum, this);

    }

    var pubtreeReload = function (themeid) {
        //同步发布树
        initPubTree({
            id: "-1",
            workSpaceId: workSpaceId,
            sort: themePubTreeSort
        });
        //修改应用页面信息
        $.ajax({
            url: contextPath + '/api/ai/resource/analyse/info',
            method: 'POST',
            data: {
                id: themeid,
            },
            success: function (data) {
                var dataInfo = data.data;
                $('#app-num').text(dataInfo.appNum);
                $('#flow-num').text(dataInfo.flowNum);
                //已发布的资源列表
                renderPublishScence(themeid);
            }
        })
    }

    var pubtreeNameUpdate = function (data) {
        $pubThemeTree.gtree("updateItemName", data.id, data.name);
        $('.tempo-ai-app-rightzone-top span[id="ca-name"]').text(data.name).attr('title', data.name);
    }

    var serviceStatusUpdate = function (status, id) {
        $('div[objid="' + id + '"] .tempo-ai-app-rightzone-mid-right-info span[id="service_status"]').text(status);
    }

    var loadPublishNum = function () {
        $.ajax({
            url: contextPath + '/api/ai/resource/analyse/info',
            method: 'POST',
            data: {
                id: theme.id,
            },
            success: function (data) {
                var dataInfo = data.data;
                $('#app-num').text(dataInfo.appNum);
                $('#flow-num').text(dataInfo.flowNum);
            }
        })
    }

    var initTabs = function () {
        var workSpaceType = $themeContainer.attr("workspacetype");
        if (workSpaceType == "self") {
            $(".tempo-strap-panel-tabs").hide();
        }
        if (!isSJRY) {
            $themeTabs.find("li:eq(1)").addClass("ui-state-disabled");
        } else {
            $themeTabs.on("click", "li", function (event, appId) {
                $(this).addClass("tempo-strap-panel-tabs-selected").siblings().removeClass("tempo-strap-panel-tabs-selected");
                var href = $(this).attr("_href");
                $(href).show().siblings(".tempo-strap-panel-tabs-content").hide();
                if (href == "#tempo-theme-private-ai") {
                    $(".tempo-strap-panel-title").find(".tempo-create-workspace").css("background-color", 'rgb(81, 133, 228)').removeClass("ui-state-disabled");
                    // 加载
                    if (!$themeTree.hasClass("tempo-gtree")) {
                        initExplorer({
                            id: "-1",
                            workSpaceId: workSpaceId,
                            sort: themeTreeSort
                        });
                    }
                    // 选中
                    if ($themeTree.gtree("getSelected") != null) {
                        var item = $themeTree.gtree("getSelected");
                        if (item != null && item.fileType == 'FILE') {
                            $themeTree.gtree("clickItem", item.id);
                        } else {
                            showWelcome("design");
                        }
                    } else {
                        showWelcome("design");
                    }
                } else if (href == "#tempo-theme-public-ai") {

                    $(".tempo-strap-panel-title").find(".tempo-create-workspace").css("background-color", 'rgb(228, 228, 228)').addClass("ui-state-disabled");
                    if (appId != null) {

                        // 应用跳转
                        initPubTree({
                            id: "-1",
                            workSpaceId: workSpaceId,
                            sort: themePubTreeSort,
                            searchWord: searchWord
                        });
                    } else {
                        // 加载
                        if (!$pubThemeTree.hasClass("tempo-gtree")) {

                            initPubTree({
                                id: "-1",
                                workSpaceId: workSpaceId,
                                sort: themePubTreeSort
                            });
                        }
                        // 选中
                        if ($pubThemeTree.gtree("getSelected") != null) {
                            var item = $pubThemeTree.gtree("getSelected");
                            if (item != null && (item.type == 'flow' || item.type == 'task' || item.type == 'plflow')) {
                                $pubThemeTree.gtree("clickItem", item.uuid);
                            } else if (item != null && (item.type == 'sync')) {
                                $pubThemeTree.gtree("clickItem", item.uuid);
                            } else if (item != null && (item.type == 'gray')) {
                                $pubThemeTree.gtree("clickItem", item.uuid);
                            } else {
                                showWelcome("publish");
                            }
                        }else {
                            showWelcome("publish");
                        }
                    }
                }
            });
        }
    }

    /**
     * 初始化表排序
     */
    var initTreeSortButton = function () {
        $treeSortPanel.unbind('click').bind('click', function (e) {
            configMenuOperator.showMenus(e, "design");
        });
        $pubTreeSortPanel.unbind('click').bind('click', function (e) {
            configMenuOperator.showMenus(e, "publish");
        });
    }

    /**
     * 菜单的操作
     */
    var configMenuOperator = {
        /**
         * 显示菜单
         */
        showMenus: function (event, tag) {
            var modelMenu = utils.initMenu(event, configMenuOperator.exeucteMenuFor, null, null, tag);
            if (tag == "design") {
                modelMenu.contextmenu('selectItem', themeTreeSort);
            } else {
                modelMenu.contextmenu('selectItem', themePubTreeSort);
            }
        },
    }

    var utils = {
        initMenu: function (event, selectCallBack, data, dealMenuStatusCallBack, tag) {
            var modelMenu = $("<ul/>").appendTo($("body"));
            modelMenu.css({
                "z-index": 1000
            });
            var menuData = utils.getMenusData();
            modelMenu.contextmenu({
                data: menuData,
                show: true,
                selectable: true,
                select: function (e, ui) {
                    var d = ui.linkEl.data;
                    var menuId = ui.select.id;
                    if (tag == "design") {
                        var data = {
                            id: "-1",
                            workSpaceId: workSpaceId,
                            sort: menuId,
                            searchWord: $searchBar.searchbar("getValue").trim() || ""
                        };
                        themeTreeSort = menuId;
                        switch (menuId) {
                            // 文件夹
                            case "DEFAULT" :
                                initExplorer(data);
                                break;
                            case "ASC" :
                                initExplorer(data);
                                break;
                            case "DESC" :
                                initExplorer(data);
                                break;
                        }
                    } else {
                        var data = {
                            id: "-1",
                            workSpaceId: workSpaceId,
                            sort: menuId,
                            searchWord: $pubSearchBar.searchbar("getValue").trim() || ""
                        };
                        themePubTreeSort = menuId;
                        switch (menuId) {
                            // 文件夹
                            case "DEFAULT" :
                                initPubTree(data);
                                break;
                            case "ASC" :
                                initPubTree(data);
                                break;
                            case "DESC" :
                                initPubTree(data);
                                break;
                        }
                    }
                },
                close: function () {
                    modelMenu.remove();
                }
            });
            if (dealMenuStatusCallBack) {
                dealMenuStatusCallBack.call(modelMenu, data);
            }
            var posiLeft = event.pageX - 16;
            var posiTop = event.pageY + 16;
            var screenHeight = window.innerHeight;
            var minus = screenHeight - event.pageY;
            var menuHeight = modelMenu.height();
            if (minus < menuHeight) {
                posiTop = posiTop - menuHeight;
            }

            modelMenu.contextmenu("show", {
                position: {
                    left: posiLeft,
                    top: posiTop
                },
                linkEl: this
            });
            return modelMenu;
        },
        /**
         * 获取菜单数据
         */
        getMenusData: function () {
            var menuData = [{
                text: '默认排序',
                id: 'DEFAULT'
            }, {
                text: '名称顺序',
                id: 'ASC'
            }, {
                text: '名称倒序',
                id: 'DESC'
            }]
            return menuData;
        },
    }

    var initSearchbar = function () {
        // 左侧搜索框
        $searchBar.searchbar({
            width: 173,
            isEnter: true,
            placeholder: TempoUtils.locale("aidsview.searchTip"),
            onSearch: function (text) {
                initExplorer({
                    id: "-1",
                    searchWord: text,
                    workSpaceId: workSpaceId,
                    sort: themeTreeSort
                });
            }
        });
        // 公共应用搜索框
        $pubSearchBar.searchbar({
            width: 173,
            isEnter: true,
            placeholder: TempoUtils.locale("aidsview.searchTip"),
            onSearch: function (text) {
                initPubTree({
                    id: "-1",
                    searchWord: text,
                    workSpaceId: workSpaceId,
                    sort: themeTreeSort
                });
            }
        });
    }

    var openTree = function (dialog, tag) {
        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/resource/tree/list-own-folder';
        var method = 'POST'
        $.ajax({
            url: url,
            method: method,
            data: {
                sort: 'ASC',
                workSpaceId: workSpaceId
            },
            success: function (data) {
                var treeData = dataProcess(data.data[0]);
                treeData = [treeData];
                var $folderTree = $("#folderTree");
                $folderTree.gtree({
                    idKey: "id",
                    textKey: 'name',
                    multiSelect: false,
                    data: treeData,
                    expandFirst: true,
                    isLeafNode: function () {
                        return false;
                    },
                    getItemIcon: function (nodeData) {
                        return 'tempo-ui-icon-api-folder-close';
                    },
                    onSelect: function (data) {
                        curFolderId = data.id;
                        if (data.parentId != null && data.parentId != "-1") {
                            curPFolderId = data.parentId
                        }
                    },
                    enableSelect: true,
                    renderComplete: function () {
                        $folderTree.gtree("expand", "-1");
                    }
                });
            }
        }).done(function () {
            process.tempoprogressbar("destroy");
        });
    }
    var createThemeFromTemplate = function (id, name) {
        tag = "pub"
        curFolderId = "";
        curPFolderId = "";
        var folderid = "";
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-move'
        });
        dialog.append("<div style='width:100%;height:100%; text-align: center; margin-top: 10px;'><form><table><tr><td><label class='theme_operate_input_name'>" + TempoUtils.locale("mine.meta_grid_label_name") + "</label></td><td><input type='text' id='createThemeByTemplate' class='tempo-validatebox tempo-validator' style='width: 266px'></td></tr></table></form><div id='folderTreeDiv'><div id='folderTree'></div></div></div>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 400,
            resizable: false,
            title: TempoUtils.locale("aidsview.create_theme_from_template"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    folderid = curFolderId;
                    var form = dialog.find("form");
                    if (!form.formValidate()) {
                        return;
                    }
                    var themeName = dialog.find("input").val();
                    if(themeName.length > 60){
                        themeName = themeName.substring(0,60);
                    }
                    var url = contextPath + '/api/ai/resource/analyse/create-by-template';
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: {
                            id: id,
                            folderId: folderid,
                            themename: themeName,
                            workSpaceId: $(".theme-container").attr('workspaceid')
                        },
                        success: function (data) {
                            if (data && data.success) {
                                data.data.fileType = 'FILE';
                                data.data.belong = "1";
                                // 父id需要重新赋值，这里取folderId
                                data.data.parentId = data.data.folderId;
                                if ($(".theme-container").attr("workspacetype") != "self" && data.data.parentId == "-1") {
                                    // 工作空间根目录下新建
                                    $themeTree.gtree('loadAndSelectItem', data.data, null);
                                } else {
                                    $themeTree.gtree('loadAndSelectItem', data.data, data.data.folderId);
                                }
                                hideTemplate();
                                dialog.dialog("destroy").remove();
                            } else {
                                failTip(data.message);
                            }
                            progressbar.tempoprogressbar("destroy");
                        }
                    })

                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        openTree(dialog, tag);
        //46598 对基于案例创建这块应用名称填入值显示进行截断处理
        //默认截取前60个字符 与平台内得应用创建名称保持一致
        if (name.length > 10) {
            name = name.substring(0, 60);
        }
        $("#createThemeByTemplate").val(name);
        nameValid(dialog.find("#createThemeByTemplate"));
        // createThemeNameByTemolateValid(dialog.find("#createThemeByTemplate"));

    }

    var addThemeToobarSelectClass = function (ele) {
        ele.removeClass("ui-button");
        ele.removeClass("tempo-button");
        ele.addClass("theme-strap-header-toolbar-select");
    }

    // 修改新建任务的方式，通过加载远程页面和组件，来打开新增框，与模型仓库新建任务共用
    // 2019年9月21日 16点15分
    // @guanyb
    var createTask = function (flowInfo) {
        $m.loadHtml(contextPath + "/api/ai/view/load/app-single-task-dialog", $('body'), 'tempo-app-add-task-dialog', {
            callback: function (task, job) {
                var leaf = {};
                var trigger = job.trigger;
                leaf.id = job.id;
                leaf.name = trigger.name;
                leaf.userName = flowInfo.userName;
                leaf.parentId = flowInfo.id;
                leaf.type = 'task';
                leaf.fileType = 'FILE';
                leaf.uuid = job.id;
                $pubThemeTree.gtree("addItem", leaf, flowInfo.uuid);
                $pubThemeTree.gtree('clickItem', leaf.uuid);
            },
            data: flowInfo
        });
    }

    var deleteTask = function (flowInfo) {
        var id = flowInfo.id;
        var uuid = flowInfo.uuid;
        $("<div>").confirm({
            width: 500,
            height: 197,
            msg: TempoUtils.locale("aidsview.delete_task_confirm"),
            ok: function () {
                var progressbar = $("<div/>").tempoprogressbar();
                $.post(contextPath + "/api/ai/app/schedule/info", {"id": id}, function (info) {
                    if (info.success && info.data) {
                        var jobinfo = info.data;
                        var triggerid = jobinfo.jobId;
                        $.post(contextPath + "/api/ai/app/schedule/job/delete", {
                            "id": id,
                            "triggerId": triggerid
                        }, function (rs) {
                            progressbar.tempoprogressbar("destroy");
                            if (rs.success) {
                                failTip(TempoUtils.locale("aidsview.theme_delete_tip"));
                                $pubThemeTree.gtree('removeItem', uuid);
                                showWelcome("publish");
                            } else {
                                failTip(rs.message);
                            }
                        });
                    } else {
                        progressbar.tempoprogressbar("destroy");
                        failTip(info.message);
                    }
                });
            }
        });
    }

    var validateForm = function (dialog, isEdit) {
        var v = dialog.find('form').formValidate();
        var jobconfig = TempoUtils.getRecord(dialog.find('form'));
        var triggerName = jobconfig.name;
        var isRaname = false;
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listAllTriggerName',
            type: 'post',
            async: false,
            success: function (triggerNames) {
                if (triggerNames) {
                    isRaname = triggerNames.indexOf(triggerName) > -1;
                }
            }
        });
        if (isRaname) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.triggernameerror"), height: 180});
            return false;
        }
        return v && (function () {
            console.log(jobconfig);
            if (jobconfig.starttime && jobconfig.endtime) {
                var s = new Date(jobconfig.starttime);
                var e = new Date(jobconfig.endtime);
                if (s.getTime() > e.getTime()) {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.shengxiaoshijianerror"), height: 180});
                    return false;
                }
            }
            if (jobconfig.stime && jobconfig.etime) {
                if (jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.kaishishijianerror"), height: 180});
                    return false;
                }
                if (jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
                    $("<div/>").alert({msg: TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height: 180});
                    return false;
                }
            }
            return true;
        })();
    }

    var saveTaskConfig = function (dialog, flowInfo) {
        if (!validateForm(dialog, flowInfo)) {
            return;
        }
        var job = {
            trigger: {},
            publishFlowIds: []
        };
        var triggerParam = {};
        var trigger = job.trigger;
        var publishFlowIds = [];
        var publishFlowNames = [];
        // 调度信息
        var jobconfig = dialog.find('#tempo-mine-flow-config').serializeArray();

        // 添加对复选框值的处理，转变为一个属性值
        $.each(jobconfig, function (index, item) {
            if (!item.name.startsWith('flow_')) {
                if (trigger[item.name]) {
                    if (Array.isArray(trigger[item.name])) {
                        trigger[item.name].push(item.value);
                    } else {
                        trigger[item.name] = [trigger[item.name], item.value];
                    }
                } else {
                    trigger[item.name] = item.value;
                }
            }
        });
        // 解决IE10下面选中保存不了问题
        var isChecked = dialog.find('input[name=retry]').is(':checked');
        if (!trigger.retry && isChecked) {
            trigger.retry = 'on';
        }

        if ((dialog.find('input[name=dayofweek]').length && !trigger['dayofweek'])
            || (dialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
            $("<div/>").alert({msg: TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height: 180});
            return false;
        }
        // 处理数组类型值，转换为逗号分割的字符串
        Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
        Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
        trigger['dayofweek'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
        trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
        delete trigger['dayofweek'];
        delete trigger['dayofmonth'];
        console.log(JSON.stringify(trigger))
        trigger.interval = Number(trigger.interval);
        if (trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);
        var relatedFlow = [];
        var rflowObj = {};
        rflowObj["flow_current"] = flowInfo.id;
        relatedFlow.push(rflowObj);
        triggerParam.flowsInJob = relatedFlow;
        job.publishFlowIds = flowInfo.id;
        job.publishFlowNames = flowInfo.name;
        ;
        // 流程配置参数
        triggerParam.flowsParam = {};
        triggerParam.flowsParam[flowInfo.id] = getCurrentFlowParams(dialog);
        job.trigger.param = JSON.stringify(triggerParam);
        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/schedule/job/save';
        $.ajax({
            url: url,
            type: 'post',
            data: JSON.stringify(job),
            contentType: 'application/json',
            success: function (obj) {
                process.tempoprogressbar("destroy");
                if (obj && obj.data && obj.data.status) {
                    $('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
                    dialog.dialog("destroy");
                } else {
                    $("<div/>").alert({msg: obj.data.error, height: 180, width: 400});
                }
            },
            error: function (data) {
                process.tempoprogressbar("destroy");
            }
        });

    }

    var getCurrentFlowParams = function (dialog) {
        var paramsTable = dialog.find('#flowParamsContainer table');
        var currentFlowParams = []
        var paramsLine = paramsTable.find('tbody tr');
        paramsLine.each(function (i) {
            var paramName = $(this).find('input.flow_paramname').val();
            var paramType = $(this).find('input.flow_paramtype').val();
            var paramId = $(this).find('input.flow_paramid').val();
            var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
            var param = {};
            param.paramName = paramName;
            param.paramValue = paramValue;
            param.paramId = paramId;
            param.paramType = paramType;
            if (!$.isEmptyObject(param)) {
                currentFlowParams.push(param);
            }
        });
        return currentFlowParams;
    }

    var setFlowParams = function (dialog, flowInfo) {
        var flowid = flowInfo.id;
        dialog.find('#flowParamsContainer').hide();
        var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
        dialog.find("#publish-mine-job-param-label").text(flowInfo.name + '-' + paramLabel);
        var grid = dialog.find('#setFlowParamTable').find('tbody').empty();
        $.ajax({
            url: contextPath + "/api/ai/app/schedule/flowparams/get/" + flowid,
            type: 'post',
            success: function (result) {
                if (result && result.data && result.data.length > 0) {
                    initParamGrid(dialog, result.data);
                }
            }
        });
    }

    var getFlowParams = function (type, paramValueInput, value, nodeType) {
        var pss = [];
        if (type == 'datasource') {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/node/io/list-datasources',
                type: 'post',
                success: function (rs) {
                    process.tempoprogressbar("destroy");
                    var data = rs.data || [];
                    var itemHtml = [];
                    for (var i = 0; i < data.length; i++) {
                        var dataItem = data[i];
                        // 屏蔽模型数据源、presto数据源、impala数据源
                        if (nodeType == 'readrdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
                                continue;
                            }
                        }
                        if (nodeType == 'writerdbms') {
                            if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }

                        if (nodeType == 'readhive') {
                            if (dataItem.type != 'hive') {
                                continue;
                            }
                        }
                        if(nodeType == 'writehive'){
                            if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
                                continue;
                            }
                        }
                        if (nodeType == "readinfluxdb") {
                            if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
                                continue;
                            }
                        }
                        if( nodeType == "readiotdb"){
                            if (dataItem.type != 'iotdb') {
                                continue;
                            }
                        }
                        if( nodeType == "writeiotdb"){
                            //不是iotdb  或者不能写入
                            if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
                                continue;
                            }
                        }
                        itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
                    }
                    var html = itemHtml.join('');
                    paramValueInput.html(html);
                    paramValueInput.selectmenu({
                        editable: false,
                        width: 150,
                        labelForTitle: true
                    }).selectmenu('setValue', value).selectmenu('refresh');
                }
            });
        } else {
            var items = TempoMineUtils.getConstFlowParams();
            if (items) {
                for (name in items) {
                    pss.push('<option value="' + name + '">' + items[name] + '</option>')
                }
            }
            var html = pss.join('');
            paramValueInput.html(html);
            paramValueInput.selectmenu({
                editable: true,
                width: 150,
                labelForTitle: true
            }).selectmenu('setValue', value);
        }

    }

    var initParamGrid = function (dialog, ps) {
        var grid = dialog.find('#setFlowParamTable');
        dialog.find('#flowParamsContainer').show();
        if (ps && ps.length > 0) {
            for (var i = 0; i < ps.length; i++) {
                var tr = $('<tr>').appendTo(grid);
                var p = ps[i];
                var paramName = p.paramName;
                var paramValue = p.paramValue;
                var paramType = p.paramType;
                var paramId = p.paramId;
                var nodeType = p.nodeType;
                var paramNameTd = $('<td>').appendTo(tr);
                var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName);
                var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
                var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
                var paramValueTd = $('<td>').appendTo(tr);
                var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
                paramNameInput.validatebox({width: 100, readonly: true});

                paramNameInput.attr('title', paramName);
                getFlowParams(paramType, paramValueInput, paramValue, nodeType);
            }
        }
    };

    var initFormData = function (dialog) {
        TempoUtils.parserUi(dialog, {});
        dialog.find('input[name="retry"]').checkbox({
            change: function (e, ui) {
                console.log(e, ui);
                if (ui.checked) {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: false, required: true});
                } else {
                    dialog.find('input[name="retryNum"]').numberbox({disabled: true, required: false});
                }
            }
        });

        dialog.find('.datefield').datepicker({
            dateFormat: 'yy-mm-dd',
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            onChangeMonthYear: function (year, month, inst) {
                var month = inst.selectedMonth + 1;
                var day = inst.selectedDay;
                var format = function (v) {
                    return String(v).length > 1 ? v : ('0' + v)
                }
                $(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
                $.datepicker._hideDatepicker(this);
            }
        });
        dialog.find('.timefield').timepicker({
            onClose: function () {
                if ($(this).val()) {
                    $(this).validatebox('response', $(this).val());
                }
            },
            onSelect: function () {

            },
            timeInput: true
        });

        var internalInput = dialog.find('input[name=interval]');
        dialog.find('select[name="triggertype"]').selectmenu({
            selectFirst: false,
            change: function (e, ui) {
                console.log(e, ui);
                changeTriggerType(ui.item.value);
            }
        });

        var changeTriggerType = function (value) {
            if (value == "-2") {
                // 分钟
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
                internalInput.numberbox({max: 59, min: 1}).val(30);
            } else if (value == "-1") {
                // 小时
                switchShowItem(dialog, false, true, false, true, 1);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
                internalInput.numberbox({max: 23, min: 1}).val(3);
            } else if (value == "0") {
                // 天
                switchShowItem(dialog, false, false, true, true, 3);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
                internalInput.numberbox({max: 31, min: 1}).val(1);
            } else if (value == "1") {
                // 周
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
                switchShowItem(dialog, true, false, true, false);
                buildWeeks(dialog);
                internalInput.numberbox({max: 6, min: 1}).val(1);
            } else if (value == "2") {
                // 月
                switchShowItem(dialog, true, false, true, true, 2);
                dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
                buildDays(dialog);
                internalInput.numberbox({max: 11, min: 1}).val(1);
            }
        }

        dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
        changeTriggerType(0);
        dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
    }

    /**
     * 调度时间切换方法
     */
    var switchShowItem = function (dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
        var _onoff = $.fn.onoff;
        $.fn.onoff = function (value) {
            var element = $(this);
            if (value) {
                element.show();
            } else {
                element.hide();
            }
            element.find('input').each(function (index, ele) {
                var role = $(ele).attr('ui-role');
                if (role == 'validatebox' || role == 'numberbox') {
                    !value ? $(ele)[role]('disable') : $(ele)[role]('enable');
                }
            });
        }
        dialog.find('.times-row').onoff(timesRow);
        dialog.find('.times-board').empty();
        if (timeRange) {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: true}).validatebox('validate');
        } else {
            dialog.find('.day-of-time-range-row input[name=stime]')
                .validatebox({required: false}).validatebox('validate');
        }
        dialog.find('.day-of-time-range-row').onoff(timeRange);
        dialog.find('.day-of-time-row').onoff(dayTime);
        dialog.find('.time-interval-row').onoff(interval);
        if (interval && dayMonthYear != undefined) {
            dialog.find('.time-of-day').onoff(dayMonthYear == 1);
            dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
            dialog.find('.day-of-month').onoff(dayMonthYear == 2);
            dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
            dialog.find('.month-of-year').onoff(dayMonthYear == 3);
            dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
        }
        $.fn.onoff = _onoff;
    }

    /**
     * 构建周页面
     */
    var buildWeeks = function (dialog) {
        var board = dialog.find('.times-board');
        var weeks = [2, 3, 4, 5, 6, 7, 1];
        var weekName = [TempoUtils.locale("mine.xinqiyi"),
            TempoUtils.locale("mine.xinqier"),
            TempoUtils.locale("mine.xinqisan"),
            TempoUtils.locale("mine.xinqisi"),
            TempoUtils.locale("mine.xinqiwu"),
            TempoUtils.locale("mine.xinqiliu"),
            TempoUtils.locale("mine.xinqitian")
        ];
        weeks.forEach(function (e, i) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
            $("<label/>").text(weekName[i]).appendTo(span);
        });
        TempoUtils.parserUi(board, {});
    };

    /**
     * 构建天页面
     */
    var buildDays = function (dialog) {
        var board = dialog.find('.times-board');
        for (var i = 1; i <= 31; i++) {
            var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
            $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
                .val(i)
                .addClass('day-of-month-' + i)
                .appendTo(span);
            $("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
        }
        var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
        $("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
            .val("L")
            .addClass('day-of-month-L')
            .appendTo(lastSpan);
        $("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
        TempoUtils.parserUi(board, {});
    }

    var modifyInfo = function (data) {
        $('.tempo-ai-app-rightzone-top span[id="task-creator"]').text(data.userName).attr("title", data.userName);
        var catime = new Date(data.createTime).Format("yyyy-MM-dd hh:mm:ss");
        $('.tempo-ai-app-rightzone-top span[id="task-time"]').text(catime);
        $.ajax({
            url: contextPath + '/api/ai/mineresource/getThemeNameByCategoryId',
            method: 'POST',
            data: {
                id: data.parentId
            },
            success: function (themeName) {
                $('.tempo-ai-app-rightzone-top span[id="task_belong_theme"]').text(themeName).attr("title", themeName);
            }
        });
        $.ajax({
            url: contextPath + '/api/ai/mine/publish/listJobInfo',
            type: 'post',
            dataType: 'json',
            data: {
                id: data.id
            },
            success: function (result) {
                if ("true" == result.flag) {
                    var job = result.job;
                    var taskStatusDesc = "生效";
                    if (job.trigger.status == "PAUSED" || job.trigger.status == "PAUSED_BLOCKED") {
                        taskStatusDesc = '暂停';
                    } else if (job.trigger.status == "COMPLETE") {
                        taskStatusDesc = '失效';
                    } else if (job.trigger.status == "AWAIT") {
                        taskStatusDesc = '等待';
                    }
                    console.log("next time: " + job.trigger.nexttime);
                    $('.tempo-ai-app-rightzone-top span[id="task-createTime"]').text(formatCreateTime(job.createTime));
                    $('.tempo-ai-app-rightzone-top span[id="ca-name"]').text(job.trigger.name).attr('title', job.trigger.name);
                    $('.tempo-ai-app-rightzone-mid span[class="task-runtStatus"]').text(taskStatusDesc).attr("id", data.id);
                }
            }
        });
    }

    var loadTaskRightPage = function (data) {
        $('.tempo-ai-app-rightzone-mid li.unsort').show();
        $('.tempo-ai-app-rightzone-mid').off('click').on('click', "li", function (e) {

            $('.welcome-page-2').hide();
            var vurl = $(e.target).data("v");
            $(this).siblings().removeClass("tempo-ai-app-rightzone-mid-select");
            $(this).addClass("tempo-ai-app-rightzone-mid-select");
            if (vurl == null) {
                return;
            }
            $rightappView.find('.tempo-ai-app-rightzone-bot-service').empty();
            $rightTaskView.find('.tempo-ai-app-rightzone-bot').empty();
            var id = data.id;
            if ("overview" == vurl) {
                id = data.parentId;
            }
            $m.loadPage(contextPath + "/api/ai/app/view/" + vurl + "?id=" + id + "&&t=" + TempoUtils.uuid() + "&&serviceId=" + data.parentId, $rightTaskView.find('.tempo-ai-app-rightzone-bot'));
        })
        $rightTaskView.find('.tempo-ai-app-rightzone-mid li:eq(0)').trigger('click');
    }

    /**
     * 分享成果
     * @param data
     */
    var shareApp = function (data) {
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-shareapp'
        });
        dialog.append("<div id='folderTreeDiv'><div id='folderTree'></div></div>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 400,
            resizable: false,
            title: TempoUtils.locale("aidsview.share_achievement"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var selected = $('#folderTree').gtree('getSelected');
                    if (selected.id == -1) {
                        failTip(TempoUtils.locale("aidsview.select_one_level"));
                        return;
                    }
                    var parentId = selected.id;
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.post(contextPath + '/api/ai/app/category/add', {
                        parentId: parentId,
                        id: data.id
                    }, function (result) {
                        progressbar.tempoprogressbar("destroy");
                        if (result.success) {

                            TempoUtils.showTip(TempoUtils.locale("aidsview.app_share_success"));
                            var treeData = $pubThemeTree.find(".tempo-gtree-item");
                            // $pubThemeTree.gtree("updateItemParam", data.uuid,"modeltype" ,"WAREHOUSE");
                            if ($rightappView.hasClass("tempo-ai-huidu")) {
                                //灰度服务下同步服务
                                for (var i = 0; i < treeData.length; i++) {
                                    if (data.id === $(treeData[i]).data("data").id) {
                                        $pubThemeTree.gtree("updateItemParam", $(treeData[i]).data("data").uuid, "modeltype", "WAREHOUSE");
                                    }
                                }
                            } else if ($rightGrayView.hasClass("tempo-ai-huidu")) {
                                //显示取消分享按钮
                                grayShareFlag = true;
                            } else {
                                for (var i = 0; i < treeData.length; i++) {
                                    if (data.id === $(treeData[i]).data("data").id) {
                                        $pubThemeTree.gtree("updateItemParam", $(treeData[i]).data("data").uuid, "modeltype", "WAREHOUSE");
                                    }
                                }
                            }
                            $selectBtn.show();
                            showSharePath(data.id);
                            $shareBtn.hide();
                        } else {
                            TempoUtils.showTip(result.message);
                        }
                        dialog.dialog("destroy").remove();
                    });
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        openModelHubTree(dialog);
    }


    // 取消分享成果
    var unshareApp = function (data) {
        $("<div>").confirm({
            width: 500,
            height: 197,
            msg: TempoUtils.locale("aidsview.app_cancel_share_confirm"),
            ok: function () {

                var progressbar = $("<div/>").tempoprogressbar();
                $.post(contextPath + "/api/ai/app/category/delete", {"id": data.id, type: 'warehouse'}, function (rs) {
                    if (rs && rs.success) {
                        var treeData = $pubThemeTree.find(".tempo-gtree-item");
                        failTip(TempoUtils.locale("aidsview.app_cancel_share_success"));
                        if ($rightappView.hasClass("tempo-ai-huidu")) {
                            //灰度服务下同步服务
                            for (var i = 0; i < treeData.length; i++) {
                                if (data.id === $(treeData[i]).data("data").id) {
                                    $pubThemeTree.gtree("updateItemParam", $(treeData[i]).data("data").uuid, "modeltype", "PRIV");
                                }
                            }
                        } else if ($rightGrayView.hasClass("tempo-ai-huidu")) {
                            grayShareFlag = false;
                        } else {
                            for (var i = 0; i < treeData.length; i++) {
                                if (data.id === $(treeData[i]).data("data").id) {
                                    $pubThemeTree.gtree("updateItemParam", $(treeData[i]).data("data").uuid, "modeltype", "PRIV");
                                }
                            }
                        }
                        $selectBtn.hide();
                        $sharePath.hide();
                        $shareBtn.show();
                    } else {
                        failTip(rs.message);
                    }
                    progressbar.tempoprogressbar("destroy");
                });
            }
        });
    }

    /**
     * 调整成果目录
     * @param data
     * @param ca
     */
    var appSelectTarget = function (data, ca) {
        var dialog = $("<div/>", {
            'class': 'tempo-theme-operate-changeapp'
        });
        dialog.append("<div id='folderTreeDiv'><div id='folderTree'></div></div>");
        dialog.dialog({
            modal: true,
            width: 500,
            height: 400,
            resizable: false,
            title: TempoUtils.locale("aidsview.app_select_target"),
            buttons: [{
                text: TempoUtils.locale("aidsview.theme_sure"),
                click: function () {
                    var selected = $('#folderTree').gtree('getSelected');
                    if (selected.id == -1) {
                        failTip(TempoUtils.locale("aidsview.select_one_level"));
                        return;
                    }
                    var parentId = selected.id;
                    var progressbar = $("<div/>").tempoprogressbar();
                    $.post(contextPath + '/api/ai/app/category/move', {
                        parentId: parentId,
                        id: data.id
                    }, function (res) {
                        progressbar.tempoprogressbar("destroy");
                        if (res.success) {
                            if (res.data != null) {
                                $("#share_directory")
                                    .html(res.data.path)
                                    .attr({
                                        "title": res.data.path,
                                        "pid": res.data.id,
                                        "folderid": res.data.parentId
                                    })
                            }
                            TempoUtils.showTip(TempoUtils.locale("aidsview.app_select_target_success"));
                        } else {
                            TempoUtils.showTip(res.message);
                        }
                        dialog.dialog("destroy").remove();
                    });
                }
            }, {
                text: TempoUtils.locale("aidsview.theme_cancel"),
                click: function () {
                    dialog.dialog("destroy").remove();
                }
            }],
            close: function () {
                // 销毁弹出框,并返回
                dialog.dialog("destroy").remove();
            }
        });
        openModelHubTree(dialog, ca);
    }

    var openModelHubTree = function (dialog, ca) {
        var process = $("<div/>").tempoprogressbar();
        var url = contextPath + '/api/ai/app/category/tree';
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                id: '-1'
            },
            success: function (data) {
                var treeData = dataProcess(data.data[0]);
                treeData = [treeData];
                var $folderTree = $("#folderTree");
                $folderTree.gtree({
                    idKey: "id",
                    textKey: 'name',
                    multiSelect: false,
                    data: treeData,
                    expandFirst: true,
                    isLeafNode: function () {
                        return false;
                    },
                    getItemIcon: function (nodeData) {
                        return 'tempo-ui-icon-api-folder-close';
                    },
                    onSelect: function (data) {
                        var item = $(this);
                        $updateNameBtn.show();
                        treeSelectIconChange(item, $folderTree, data)
                    },
                    enableSelect: true,
                    renderComplete: function () {
                        $folderTree.gtree("expand", "-1");
                        if (ca != null) {
                            if (ca.folderid == "-1") {
                                $folderTree.gtree("clickItem", ca.pid)
                            } else {
                                $folderTree.gtree("clickItem", ca.folderid);
                                $folderTree.gtree("clickItem", ca.pid)
                            }
                        }
                    }
                });
            }
        }).done(function () {
            process.tempoprogressbar("destroy");
        });
    };

    /**
     * 请求服务状态
     * @param fn
     * @param uid
     */
    var isAlive = function (fn, uid) {
        var id = uid || row.id
        $.postForm({
            url: contextPath + '/api/ai/app/model/status/' + id,
            success: function (rp) {
                fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data);
            }
        });
    }

    var updateStatusLoop = function (id, updateFn, type) {
        if (type != 'sync' && type != 'stream') {
            window.loopUpdateTimer = -1;
            return;
        }
        var timer = setTimeout(function () {
            var fn = arguments.callee;
            isAlive(function (d, status) {
                if (window.loopUpdateTimer != timer) {
                    return;
                }
                if (status == 'STARTING') {
                    $('div[objid="' + id + '"] a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                    serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    if (serviceStatus == "" || serviceStatus == null) {
                        serviceStatus = "启动中";
                    }
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    timer = setTimeout(fn, 1000);
                    window.loopUpdateTimer = timer
                } else if (status == 'RUNNING') {
                    if (typeof row != "undefined") row.launchState = status;
                    $('div[objid="' + id + '"] a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                    $('div[objid="' + id + '"] #ca-status').text(TempoUtils.locale("aiview.serviceHasStart"));
                    $("div[objid='" + id + "'] #service_status").text(TempoUtils.locale("aiview.serviceHasStart"));
                    serviceStatus = TempoUtils.locale("aiview.serviceHasStart");
                    if (serviceStatus == "" || serviceStatus == null) {
                        serviceStatus = "已启动";
                    }
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    $('a.start-button').removeClass("ui-state-disabled");
                    if (updateFn) updateFn();
                } else {
                    $('div[objid="' + id + '"] a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                    $('div[objid="' + id + '"] #ca-status').text(TempoUtils.locale("aiview.serviceUnStart"));
                    $("div[objid='" + id + "'] #service_status").text(TempoUtils.locale("aiview.serviceUnStart"));
                    serviceStatus = TempoUtils.locale("aiview.serviceUnStart");
                    if (serviceStatus == "" || serviceStatus == null) {
                        serviceStatus = "未启动";
                    }
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    $('a.start-button').removeClass("ui-state-disabled");
                    if (updateFn) updateFn();
                }
            }, id);
        });
        window.loopUpdateTimer = timer;
    }
    Eventbus.bind('updateStatusLoop.service', updateStatusLoop);
}

$(function () {
    var aiTheme = new AiTheme();
    aiTheme.init();
});